I am new to coding, so I would like to know how I can count words of an website with javascript. Should I use .innerText and a for loop?
4 Answers
Split on regular expression /\W+/ (\W matches anything that is not a latin letter or arabic number or an underscore) :
var text = "These are two sentences. They have ten words in total."; alert(text.split(/\W+/).length) More details on regexp can by found on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
5 Comments
Sebastian Simon
\W+ would be better.ben
@Xufox Any case where not having the
+ would give wrong result ?Sebastian Simon
"These are two sentences. They have ten words in total.".split(/\W/).length would give 12 because the empty strings after . are counted as well.Sebastian Simon
Other than that, this is the best solution so far as this even allows em-dashes etc. to delimit words. But what about normal dashes? For example, is
camel-case two words or one?Sebastian Simon
Also, the description is wrong (“
\W match words”). It should be “\W matches anything that is not a latin letter or arabic number or an underscore”.This is how I would count the number of words as you type:
$(document).ready(function(){ $("#count").on("keyup", function(){ $("#num").html($("#count").html().split(" ").length-1); }); }); Comments
This will do the trick for you if the language on the site uses spaces to separate words.
$.fn.showWordCount = function (){ "use strict"; var $targ = $(this); var words = $targ.html().split(' '); var wordCount = words.length; alert(wordCount); }; $('body *').showWordCount(); Proof it works: http://codepen.io/nicholasabrams/pen/rVJPOx
.innerText.split(" ").lengthmaybe?