Skip to content

Instantly share code, notes, and snippets.

@shettayyy
Last active April 30, 2020 22:57
Show Gist options
  • Save shettayyy/4b54e9322944b712db3ee18e86f05695 to your computer and use it in GitHub Desktop.
Save shettayyy/4b54e9322944b712db3ee18e86f05695 to your computer and use it in GitHub Desktop.
Get the character count of the characters present in the string https://jsbin.com/nuraxun
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
// This code is much faster than using a regex for checking if a value is alphanumeric
function isAlphaNumeric(char) {
code = char.charCodeAt(0);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
return true;
};
// Get the character count of the characters present in the string
function charCount(str) {
const result = {};
for(let char of str) {
if(isAlphaNumeric(char)) {
const charLower = char.toLowerCase();
result[charLower] = (result[charLower] || 0) + 1;
}
}
return result;
}
console.log(charCount('This is a sentence'));
</script>
<script id="jsbin-source-javascript" type="text/javascript">// This code is much faster than using a regex for checking if a value is alphanumeric
function isAlphaNumeric(char) {
code = char.charCodeAt(0);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
return true;
};
// Get the character count of the characters present in the string
function charCount(str) {
const result = {};
const strLower = str.toLowerCase();
for(let char of strLower) {
if(isAlphaNumeric(char)) {
result[char] = (result[char] + 1) || 1;
}
}
return result;
}
console.log(charCount('This is a sentence'));</script></body>
</html>
// This code is much faster than using a regex for checking if a value is alphanumeric
function isAlphaNumeric(char) {
code = char.charCodeAt(0);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
return true;
};
// Get the character count of the characters present in the string
function charCount(str) {
const result = {};
for(let char of str) {
if(isAlphaNumeric(char)) {
const charLower = char.toLowerCase();
result[charLower] = (result[charLower] || 0) + 1;
}
}
return result;
}
console.log(charCount('This is a sentence'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment