2

我想检查一个字符串中有多少个单词

例如。

 asdsd sdsds sdds 

3 个字

问题是,如果两个子字符串之间有多个空格,则结果不正确。

这是我的程序

function trim(s) {   
  return s.replace(/^\s*|\s*$/g,"")   
} 

var str = trim(x[0].value);
var parts = str .split(" ");
alert (parts.length);

如何解决问题?感谢帮助

4

6 回答 6

3

您可以只使用match单词边界:

var words = str.match(/\b\w+\b/g);

http://jsbin.com/abeluf/1/edit

于 2013-06-03T06:11:18.190 回答
2
var parts = str .split(" ");
parts = parts.filter(function(elem, pos, self) {
     return elem !== "";
});

请试试这个。确保您使用最新的浏览器来使用此代码。

于 2013-06-03T06:11:07.413 回答
1

It's easy to find out by using split method, but you need to sort out if there are any special characters. If you don't have an special characters in your string, then last line is enough to work.

s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;
于 2013-06-03T06:09:30.393 回答
1

请使用这个它已经被我在我的项目中使用:

function countWords(){
    s = document.getElementById("inputString").value;
    s = s.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    document.getElementById("wordcount").value = s.split(' ').length;
}
于 2013-06-03T06:11:40.840 回答
0

一个更短的模式,试试这样的:

(\S+)

并且正则表达式引擎返回的匹配数将是您想要的结果。

于 2013-06-03T06:46:55.370 回答
0

尝试:

function trim(s) {   
  return s.replace(/^\s*|\s*$/g,"")   
} 
var regex = /\s+/gi;
var value = "this ss ";
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
console.log( wordCount );
于 2013-06-03T06:12:58.467 回答