gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:45:33 26 4
gpt4 key购买 nike

我试图计算一个句子中的单词总数。我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com