HOWTO count words in JavaScript

Here is a handy JavaScript function for counting words:

String.prototype.countWords = function(value) { // remove html tags var cleanedText = this.replace(/< .[^<>]*?>/g, ' ') // remove numbers and punctuation .replace(/[–—.(),;:!?%#$‘’“”'"_+=\/\-]*/g, '') // remove/coalesce space chars .replace(/(&nbsp;|&#160;|[ ])+/gi, ' '); // don't split "" into words, as you'll get 1 ([""]) if (cleanedText === "") { return 0; } // count words return cleanedText.split(/\W/).length; }

Leave a comment

Your email address will not be published. Required fields are marked *