This question already has answers here:
Regular Expression for accurate word-count using JavaScript
                            
                                (7个答案)
                            
                    
                6年前关闭。
        

    

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


我哪里出问题了?

最佳答案

请尝试这个:

var word = "str";
function countWords(word) {
    var s = word.length;
    if (s == "") {
        alert('count is 0')
    }
    else {
        s = s.replace (/\r\n?|\n/g, ' ')
            .replace (/ {2,}/g, ' ')
            .replace (/^ /, '')
            .replace (/ $/, '');
        var q = s.split (' ');
        alert ('total count is: ' + q.length);
    }
}

10-07 21:42