要统计文章字数并去除HTML标签,可以使用jQuery来实现。以下是一个简单的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>统计文章字数</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="article">
<p>这是一篇 <strong>示例</strong> 文章,我们需要统计它的字数。</p>
</div>
<button id="countButton">统计字数</button>
<p>字数: <span id="wordCount">0</span></p>
<script>
$(document).ready(function() {
$('#countButton').click(function() {
var articleText = $('#article').text(); // 获取文章的文本内容
var wordCount = articleText.replace(/<[^>]+>/g, '').length; // 去除HTML标签并统计字数
$('#wordCount').text(wordCount);
});
});
</script>
</body>
</html>
#article
:包含文章内容的div
。#countButton
:用于触发字数统计的按钮。#wordCount
:显示统计结果的span
。$(document).ready(function() { ... });
:确保DOM完全加载后再执行脚本。$('#countButton').click(function() { ... });
:绑定按钮点击事件。var articleText = $('#article').text();
:获取#article
元素的文本内容。var wordCount = articleText.replace(/<[^>]+>/g, '').length;
:使用正则表达式去除HTML标签,并统计剩余文本的长度。$('#wordCount').text(wordCount);
:将统计结果显示在#wordCount
元素中。/<[^>]+>/g
正确匹配所有HTML标签。trim()
)来去除多余的空格和换行符。通过以上方法,可以有效地统计文章字数并去除HTML标签,适用于多种应用场景。
领取专属 10元无门槛券
手把手带您无忧上云