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.
答案 0 :(得分: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.
答案 1 :(得分: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.
答案 2 :(得分: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.