If there is a random string get from SERVER:
var str='I am a student in XXX university, I am interested...'
The str
can contain random number of words with spaces. That's the content of the string is unpredictable.
In javascript, how to count the number of letters in the string (spaces between words are exclusive from the counting). For example "I have a car" should be counted 9 letters.
Assuming you only want alpha characters, get rid of other characters first using replace()
:
var str='I am a student in XXX university, I am interested...';
alert(str.replace(/[^A-Z]/gi, "").length);
You can add 0-9
to the [^A-Z]
character class if you want to count numbers as letters. If you only want to remove white-space, change the regular expression to /\s/g
We split every space and join the array again:
var str='I am a student in XXX university, I am interested...'
str = str.split(" ").join("");
alert(str.length);
http://jsfiddle.net/AwVBJ/
You could coiunt the number of matches using the regex \w
- which matches any alphanumeric character or [a-zA-Z]
for any alpha character
eg:
var numChars = "I have a car".match(/[a-zA-Z]/g).length;
// numChars = 9
Live example: http://jsfiddle.net/GBvCp/
And yet another way:
var str = "I have a car";
while (str.indexOf(' ') > 0) {
str = str.replace(' ' , '');
}
var strLength = str.length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With