0

I have the following code but the text from the Div ID para has the last word and first word of the next sentence joined and views it as 1 word instead of 2

Code:

var value = $('#RichHtmlField_displayContent').text();

console.log("text", value)

    if (value.length == 0) {
        $('#show_word_count').html(0);
        return;
    }

    var wordCount = value.match(/\S+/ig).length
      $('#show_word_count').html(wordCount);
    };

$(document).ready(function() {
        $('#RichHtmlField_displayContent').change(counter);
        $('#RichHtmlField_displayContent').keydown(counter);
        $('#RichHtmlField_displayContent').keypress(counter);
        $('#RichHtmlField_displayContent').keyup(counter);
        $('#RichHtmlField_displayContent').blur(counter);
});

So what I want to do is add a space after all full stops, question marks then count the total word.

Jamie Eltringham
  • 816
  • 3
  • 16
  • 25
John Smith
  • 11
  • 3
  • 1
    If you clean up your code formatting you'll notice that you have an orphaned bracket `};` in your example. Also, it would be VERY useful if you provided a working example / snippet. – Moob Apr 25 '16 at 09:03

3 Answers3

2

If you replace ths "s" in your regular expression with "w" it will search for words instead . See below -

function wordCount() {
  var value = document.getElementById("text").value;
  document.getElementById("result").innerText = value.match(/\w+/ig).length;
}

wordCount();
<textarea id="text">Some text. Here!</textarea>
<div id="result"></div>
<button onclick="wordCount()">Word Count</button>

This will match any string of letters or numbers (including underscores).

For a more in-depth discussion of regular expressions check out this question and Mozilla Developer Network.

Community
  • 1
  • 1
John C
  • 2,732
  • 2
  • 31
  • 46
0

Instead of using a RegEx match you can split the text into an array using a RegEx seperator:

var wordCount = value.split(/[\s.?]+/).length

This only splits based on whitespace, full stop and question mark as per your question (and will count words with hyphens in them as one word). You can add more word seperators to the RegEx as necessary.

wilsonzlin
  • 1,967
  • 1
  • 8
  • 21
0

You can split it using replace.

See JSFiddle.

Note: It is not optimized for all punctuations (e.g. ...), you can modify the regex to archive what you need.

theaws.blog
  • 2,001
  • 20
  • 19