Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Last active February 4, 2021 14:33
Show Gist options
  • Select an option

  • Save mustafadalga/e2fa180c3ae9b68dcbd9f7a1a1815f12 to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/e2fa180c3ae9b68dcbd9f7a1a1815f12 to your computer and use it in GitHub Desktop.
A function that takes a string and returns the count of each character in the string
function charCount(str) {
if (typeof str != "string") return;
str = str.toLowerCase()
const result = {}
str.split("").forEach(char => {
if ((/[a-z0-9]/).test(char)) {
result[char]=result.hasOwnProperty(char) ? ++result[char] : 1
}
});
return result;
}
// Example
charCount("How is going ? ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment