First off, I know this is far from professional. I\'m trying to learn how to work with strings. What this app is supposed to do is take a simple text input and do a few thi
Not sure if whole problem, but bad paren on this one
if(text.charAt(letters)) == " " && text(letters) < text.length)
^
Should be
if(text.charAt(letters) == " ") && text(letters) < text.length)
^
And actually I'd make it
if((text.charAt(letters) == " ") && (text(letters) < text.length))
Use regular expressions.
Example
var s = "thisIsAstring";
var numUpper = s.length - s.replace(/[A-Z]/g, '').length;
// numUpper = 2
Se more at JavaScript replace/regex
Another solution using CharCodeAt() method.
const bigLettersCount = (str) => {
let result = 0;
for (let i = 0; i < str.length; i += 1) {
if (str.charCodeAt(i) > 64 && str.charCodeAt(i) <91 ) {
result += 1;
}
}
return result
}
console.log(bigLettersCount('Enter some words.'))
Most of the solutions here will fail when string contains UTF8 or diacritic characters. An improved version that works with all strings can be found at the turbocommons library, here:
https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391
Example:
// Returns 2
StringUtils.countByCase('1声A字43B45-_*[]', StringUtils.FORMAT_ALL_UPPER_CASE);
// Returns 1
StringUtils.countByCase('1声A字43B45a-_*[]', StringUtils.FORMAT_ALL_LOWER_CASE);
More info here:
https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php
Play with it online here:
https://turbocommons.org/en/app/stringutils/count-capital-letters
Another solution is using Array.from()
make an array which includes each character of str
and then using reduce()
to count the number of the uppercase letters.
const str = 'HeLlO';
const res = Array.from(str).reduce((acc, char) => {
return acc += char.toUpperCase() === char;
}, 0);
console.log(res);
You can use match() and regular expressions.
var str = "aBcD";
var numUpper = (str.match(/[A-Z]/g) || []).length; // 2