如何计算随机字符串中的字母数?

问题描述:

如果从SERVER获得随机字符串:

If there is a random string get from SERVER:

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

str 可以包含带空格的随机数字。这是字符串的内容是不可预测的。

The str can contain random number of words with spaces. That's the content of the string is unpredictable.

在javascript中,如何计算字符串中的字母数(单词之间的空格 独占。例如我有一辆车应该被计为9个字母。

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.

假设你只想要字母字符,那就去掉其他的字符首先使用 replace()

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);

您可以将 0-9 添加到 [^ AZ] 字符类,如果您想将数字计为字母。如果您只想删除空格,请将正则表达式更改为 / \s / g

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