计算HTML段落的字数

Count number of words in HTML paragraphs

本文关键字:段落 HTML 计算      更新时间:2023-09-26

我有一个HTML文件,其中有几个段落具有相同的类'profile-value'。我想使用JavaScript创建一个字数,可以计算每个段落的所有单词。我已经试过了:

var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (var i = 0; i > profile_values.length; i++) {
    total_words += profile_values[i].length;
};
然后使用innerHTML: 调用total。
document.getElementById('word-count').innerHTML = total_words;

我已经看到迭代Nodelist是相当灵巧的,但在尝试上面的代码之前,我也尝试过将Nodelist转换为数组,同样无济于事。希望你们能解释清楚?

这个怎么样?https://jsfiddle.net/rrex0gju/

function getWordCounts(nodeList) {
    var wordCount = 0;
    for ( var i = 0; i < nodeList.length; i++ ) {
        wordCount += nodeList[i].textContent.trim().split(' ').length;
    }
    return wordCount;
}
document.querySelector('span').textContent = getWordCounts(document.querySelectorAll('p'));

首先获取以下段落

var paras = document.getElementsByClassName('profile-value');

然后运行代码片段以获得如下计数:

var count = 0;
for(var i=0; i<paras.length; i++){
 var content = paras[i].textContent;
 var words = content.match(/'S+/g);
 count += words? words.length : 0;
}
console.log('count = ', count);

使用上面的响应,我将代码修改为:

var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
 for (var i = 0; i < profile_values.length; i++) {
  total_words = total_words + profile_values[i].innerText.split("   ").length;
};

这似乎已经成功了。你们觉得这样对吗?我要感谢你们所有人的帮助!

使用字符串的split属性,然后获取length,得到总字数

这里trim()函数用于从字符串中删除前导尾随空间。

var profile_values = document.getElementsByClassName('profile-value');
var total = 0;
for(var i = 0; i < profile_values.length; i += 1){
  total += profile_values[i].innerHTML.trim().split(" ").length
}
alert(total);
<p class="profile-value">    sdfsf dsfsf dsfs sdfds      </p>

访问所有类profile_value:

var profile_values = document.querySelectorAll(".profile_value");

Profile_values现在是HTML集合。浏览集合:

[].forEach.call(profile_values, function(paragraph) {});

inner函数中innerText拆分为数组,其中包含所有中的单词。数组的长度是最近一段的单词数:

var splitted = paragraph.innerText.split(" ");
var countWordsParagraph = splitted.length;

添加countwordsparagh到totalWordCount:

totalWordCount += countWordsParagraph;

完成:

var profile_values = document.querySelectorAll('.profile-value'); 
var totalWordCount = 0;
[].forEach.call(profile_values, function(paragraph) {
    var splitted = paragraph.innerText.split(" ");
    var countWordsParagraph = splitted.length;
    totalWordCount += countWordsParagraph;
});
可见