admin管理员组文章数量:1391937
I would like to check how many words in a string
eg.
asdsd sdsds sdds
3 words
The problem is , if there is more than one space between two substring , the result is not correct
here is my program
function trim(s) {
return s.replace(/^\s*|\s*$/g,"")
}
var str = trim(x[0].value);
var parts = str .split(" ");
alert (parts.length);
How to fix the problem? thanks for help
I would like to check how many words in a string
eg.
asdsd sdsds sdds
3 words
The problem is , if there is more than one space between two substring , the result is not correct
here is my program
function trim(s) {
return s.replace(/^\s*|\s*$/g,"")
}
var str = trim(x[0].value);
var parts = str .split(" ");
alert (parts.length);
How to fix the problem? thanks for help
Share Improve this question asked Jun 3, 2013 at 6:07 user1871516user1871516 1,0096 gold badges15 silver badges26 bronze badges6 Answers
Reset to default 3You could just use match
with word boundaries:
var words = str.match(/\b\w+\b/g);
http://jsbin./abeluf/1/edit
var parts = str .split(" ");
parts = parts.filter(function(elem, pos, self) {
return elem !== "";
});
Please try this. Make sure you are using latest browser to use this code.
Please use this one Its already used by me in my project :
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;
}
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;
try:
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 );
An even shorter pattern, try something like this:
(\S+)
and the number of matches return by regex engine would be your desired result.
本文标签: regexCheck a string contain how many word in javascriptStack Overflow
版权声明:本文标题:regex - Check a string contain how many word in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744712303a2621201.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论