user3390793
user3390793

Reputation: 9

Detect two or more sequential empty spaces

I am learning JavaScript and could use your help. The code below actively displays the word count for the user who's typing into a textbox. My code detects an empty space and adds one to the word count.

I am trying to improve the word counter and write an if/then statement that detects two or more empty spaces in a row, and does not add to the word count. My plan was that if two empty spaces in a row were detected decrement by one, in effect nullifying the extra spaces.

Here is my code:

<!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>

Upvotes: 0

Views: 98

Answers (1)

plalx
plalx

Reputation: 43718

I would use a different approach and match all words using a regex rather than count spaces.

E.g.

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

Here's another alternative with split using a regex as well:

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

console.log(wordCount); //3

You could also implement one without regular expressions:

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;
}

Upvotes: 1

Related Questions