检测两个或多个连续的空白空间

时间:2014-03-09 01:34:24

标签: javascript if-statement

我正在学习JavaScript,可以使用你的帮助。以下代码主动显示在文本框中输入的用户的字数。我的代码检测到一个空白区域,并在单词计数中添加一个。

我正在尝试改进单词计数器并编写一个if / then语句来检测一行中的两个或多个空格,并且不会添加到单词计数中。我的计划是,如果检测到连续两个空格的空间减1,实际上会使额外的空格无效。

这是我的代码:

<!DOCTYPE HTML>
<html>
<head>
</head>

<body>

<p><textarea id="myWordsToCount" rows="5" cols="60"></textarea><br></p>

The wordcount is: <span id="wordcount"></span><br>

<script type="text/javascript">

// JavaScript Word Count

var textBoxElement = document.getElementById("myWordsToCount")   // no .value wanted sice i am detecting at the element level

textBoxElement.onkeyup = function() {

textBoxElementValues = document.getElementById("myWordsToCount").value;

var stringSplt = textBoxElementValues.split(" ");
var doublequote = textBoxElementValues.split("  ");


if ( doublequote ) {
    stringSplt.length--;
 }

document.getElementById("wordcount").innerHTML = stringSplt.length;


}


</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

我会使用不同的方法,并使用正则表达式匹配所有单词,而不是计算空格。

E.g。

var text = ' test test testing   test',
    words = text.match(/\b[^\s]+\b/g),
    wordCount = words? words.length : 0; //4

以下是使用正则表达式split的另一种选择:

var text = ' test sdftdf sdf',
    wordCount = text.split(/\s+/).filter(function (w) { return !!w; }).length;

console.log(wordCount); //3

你也可以实现一个没有正则表达式的东西:

function wordCount(text) {
    var i = 0, 
        len = (text = text + '').length,
        parsingWord = false,
        wordCount = 0;

    for (; i < len; i++) switch (text[i]) {
        case '\t':
        case ' ': parsingWord = false; break;
        default: !parsingWord && (parsingWord = true) && ++wordCount;
    }

    return wordCount;
}
相关问题