Count words with JavaScript

一世执手 提交于 2019-12-02 06:53:53

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

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

JSFiddle code here

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

May be it can help you:

<script>
var words = document.getElementsByTagName('body')[0].innerHTML.replace(/<.*?>/g, '');
console.log(words.match(/\S+/g).length);
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!