计算HTML段落的字数
Count number of words in HTML paragraphs
我有一个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;
});
可见相关文章:
- 在HTML字符串的某个段落后插入HTML
- 我怎么能在同一个HTML页面上多次在不同的段落中添加相同的字符串呢
- 如何隐藏和显示 html 输入文本和段落
- 如何获取段落的文本,然后将其转换为 HTML 中的整数
- 正则表达式用于匹配段落中的单词,但排除内部 HTML 标记
- “打开”/占卜 HTML 段落
- 内部文本不适用于段落和标题 HTML 元素
- 无法在网页上显示的 HTML 段落上叠加图像图标
- 是否可以在没有html锚点的情况下找到网页的某些段落
- 如何使用 jQuery 将段落的原始文本格式放入 HTML 段落元素中
- 仅在单击时显示段落的 HTML
- 使用 JavaScript 组合 HTML 段落
- 用 html 标记替换段落中的每个单词
- 使用 Jquery 将子字符串替换为段落中的 html 元素,而不会弄乱出现的事件
- 从HTML标题和段落创建下拉菜单
- JavaScript/HTML|使HTML段落等于用户输入
- 如何让我的javascript var在html段落中返回
- 关于将javascript中的数组插入HTML中的段落元素的基本帮助
- CSS,JavaScript,HTML-所见即所得编辑器中的空段落和错误代码
- 空白段落HTML元素不显示