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

If there is a random line from SERVER:

var str='I am a student in XXX university, I am interested...' 

str can contain a random number of words with spaces. That the contents of the string are unpredictable.

In javascript, how to count the number of letters in a string ( spaces between words are exclusive from the count). For example, β€œI have a car” should be counted 9 letters.

+6
source share
6 answers

Assuming you only need 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(/[^AZ]/gi, "").length); 

You can add 0-9 to the character class [^AZ] if you want to count numbers as letters. If you want to remove only empty space, change the regex to /\s/g

+15
source

We split each space and reattach the array:

 var str='I am a student in XXX university, I am interested...' str = str.split(" ").join(""); alert(str.length); 

http://jsfiddle.net/AwVBJ/

+7
source

You can match the number of matches using the regular expression \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 

Real-time example: http://jsfiddle.net/GBvCp/

+6
source

And one more way:

 var str = "I have a car"; while (str.indexOf(' ') > 0) { str = str.replace(' ' , ''); } var strLength = str.length; 
+2
source
 var temp = str; temp= temp.replace(/[^a-zA-Z]+/g,""); 

temp.length will give u the number of characters

+2
source

Count the number of spaces (e.g. http://p2p.wrox.com/javascript-how/70527-count-occurrence-character-string.html ), then subtract this from the length.

     var testString = 'my test string has a number of spaces';
     alert ('Number of spaces:' + (testString .replace (/ [^] / g, '') .length));
     alert ('Number of characters:' + (testString.length));
     alert ('Number of characters excluding spaces:' + 
         (testString.length - (testString .replace (/ [^] / g, '') .length)));

Note: it correctly counts double spaces and spaces at the ends.

0
source

Source: https://habr.com/ru/post/896881/


All Articles