word count in form and period, comma automatically adds spaces when it does not exist onkeyup

634 Views Asked by At

I have a code which counts the words, but also does not count words that were not preceded by a space - for example: "text,count" will be counted as one, and I care about the calculation of each game are saved words.

I want it to be automatically added after . , ; : spaces

How to change the code to make this happen.

http://jsfiddle.net/jZeKu/392/

<div id="border">
    <textarea id='text'></textarea>
</div>
<button id="count">Count</button>
<div id="result">
    Words: <span id="wordCount">0</span><br/>
    Total Characters(including trails): <span id="totalChars">0</span><br/>
    Characters (excluding trails): <span id="charCount">0</span><br/>
    Characters (excluding all spaces): <span id="charCountNoSpace">0</span>
</div>



counter = function() {
    var value = $('#text').val();

    if (value.length == 0) {
        $('#wordCount').html(0);
        $('#totalChars').html(0);
        $('#charCount').html(0);
        $('#charCountNoSpace').html(0);
        return;
    }

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



};


$(document).ready(function() {
    $('#count').click(counter);
    $('#text').change(counter);
    $('#text').keydown(counter);
    $('#text').keypress(counter);
    $('#text').keyup(counter);
    $('#text').blur(counter);
    $('#text').focus(counter);
});
2

There are 2 best solutions below

0
On

Just replace the characters you want like .replace('.', '. ')

3
On

You have to change the regex like this

 var regex =  /[\s,.;:]+/gi; 

link to JSFIDDLE