Count words with JavaScript

2019-03-02 07:34发布

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条回答
相关推荐>>
2楼-- · 2019-03-02 08:10

May be it can help you:

<script>
var words = document.getElementsByTagName('body')[0].innerHTML.replace(/<.*?>/g, '');
console.log(words.match(/\S+/g).length);
</script>
查看更多
做个烂人
3楼-- · 2019-03-02 08:19

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

查看更多
看我几分像从前
4楼-- · 2019-03-02 08:31

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

查看更多
beautiful°
5楼-- · 2019-03-02 08:32

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

查看更多
登录 后发表回答