javascript - 如何在javascript中获取字符串中的单词总数

标签 javascript regex

我试图计算一个句子中的单词总数。我在 Javascript 中使用了以下代码。

function countWords(){
    s = document.getElementById("inputString").value;
    s = s.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    alert(s.split(' ').length);
}

因此,如果我给出以下输入,

"Hello world"  -> alerts 2       //fine
"Hello world<space>" -> alerts 3 // supposed to alert 2
"Hello world world" -> alerts 3  //fine

我哪里出错了?

最佳答案

在这里你会找到你需要的一切。

http://jsfiddle.net/deepumohanp/jZeKu/

var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;

$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);

关于javascript - 如何在javascript中获取字符串中的单词总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16417580/

相关文章:

javascript - 如何开发带音效的jQuery拖拽?

java - Android Java - String .replaceAll 替换特定字符(正则表达式)

javascript - 使用javascript设置img标签的src属性

javascript - 各种 javascript 元素的跨浏览器兼容性

javascript - 将连续的 ","合并为单个 ","并在一个 RegExp 中删除前导和尾随 ","

database - PostgreSQL 字符串字符替换

java - 正则表达式,用于从html输出中提取标签之间的内容

regex - 什么是正则表达式来匹配 =,空格分隔后的所有事件?

javascript - Angular2 代码给出内联模板错误

javascript - 从 3.0 之前的 servlet 的 FormData api 检索请求参数,其中不支持 request.part