Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of letters in a random string? [closed]

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.

like image 215
Mellon Avatar asked Sep 08 '11 14:09

Mellon


4 Answers

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

like image 189
Andy E Avatar answered Nov 17 '22 15:11

Andy E


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/

like image 22
Andreas Louv Avatar answered Nov 17 '22 17:11

Andreas Louv


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/

like image 8
Jamiec Avatar answered Nov 17 '22 17:11

Jamiec


And yet another way:

var str = "I have a car";   
while (str.indexOf(' ') > 0) { 
    str = str.replace(' ' , '');
    }
var strLength = str.length;     
like image 2
CatchingMonkey Avatar answered Nov 17 '22 17:11

CatchingMonkey