# How to count the number of uppercase letters in a string?

Is there a way to count the number of uppercase letters in a string using Javascript?

I could go through each letter in the alphabet and compare it with each letter in the string, but I think this would be too slow.

Or, is there a regular expression that could tell if a string contained more than one uppercase letter?

something like this should work:

<script type="text/javascript">
str = "ThIs Is A Test On HOW tO counT UppeR CaSE";
</script>

There’s more than one way to do that. Here’s one:

function countUpperCaseChars(str) {
var count=0,len=str.length;
for(var i=0;i<len;i++) {
if(/[A-Z]/.test(str.charAt(i))) count++;
}
return count;
}

Edit: chuckles It seems that ALL thought of a more efficient way to do it.

This works beautifully - thank you, ALL!

And yes, there is always more than one way to do something. Thanks for replying as well, Kravvitz

Not using regexes:

var str = "ThIs Is A Test";
for(var i = 0, len = str.length, count=0, ch; i < len; ++i)
{
ch = str.charAt(i);
if(ch >= 'A' && ch <= 'Z') ++count;
}

It don’t show turkish characters (Ö, Ü, Ç, İ, Ğ, Ş). Turkish characters will be added this. How? Thanks…

<script type="text/javascript">
str = "&#220;&#199; tas has ho&#350;af g&#214;t&#252;r&#252;ld&#252;.";
</script>

muazzez - Unfortunately, you would have to define an array of non-latin uppercase characters and do an individual character compare.

actually yes you can but you have to add those speical characters by hand…

First you will need to findout if the character is within the 256 ascii characters and if not you will need to find out the unicode character of each one. the only two in your example that needed where the last two.

then do something like this:

<script type="text/javascript">
str = "ÜÇ tas has hoaf"+String.fromCharCode(350)+" gÖtürüldü.";
regex = new RegExp('[^A-Z\\Ö\\Ç\\Ü\\I\\\\' + String.fromCharCode(350) + '\\\\' + String.fromCharCode(286) + ']', 'g');
</script>

I used String.fromCharCode(350) for Ğ character because my browser didnt like me putting in unique characters, but if you are deriving it though a textbox you shouldn not need to worry about it. I aluse used \ characters more for a “just incase” browser compatability problem.

-ALL

ALL,
I tried your code. Message box showed 4.
Here is the code I wrote.
ÜÇ tas has hoŞaf gÖtürüldü konaĞın İçine.

<script type="text/javascript">

str = "ÜÇ tas has ho&#350;af gÖtürüldü kona&#286;&#305;n &#304;çine.";