当前位置:首页 »“秋了秋”个人博客 » 前端编程 » 获取html字符串中纯文本字数

获取html字符串中纯文本字数

作者:秋了秋 发表时间:2022年02月08日

实质就是去除html中的标签,应用场景是非浏览器环境,比如后端环境中需要输出文章摘要或者统计文章字数。

/* 获取字符串中纯文本字数
 * {html} 字符串
 * {tags} 需要计数的标签名,如['img', 'hr'],如果有这些标签,计数加1
 * {return} number 文本个数,多个换行符、制表符、空格算占位一个
 */
function getHtmlTextLength(html, tags) {
	var count = html.replace(/<[^<]+>/g, '').replace(/[\n\t\s]+/g, ' ').length;
	if(tags) {
		var reg = '<('+tags.join('|')+')[^<]+>';
		var matchs = html.match(new RegExp(reg, 'g'));
		if(matchs && matchs.length) {
			count += matchs.length;
		}
	}
	return count;
}

如果是浏览器环境,可直接使用浏览器api实现:

function getHtmlTextLength(html) {
	var span = document.createElement('span');
	span.innerHTML = html;
	return span.innerText.length;
}

使用示例:

getHtmlTextLength(`<h1 class="title-article" id="articleContentId">提取html字符串特定的文字内容</h1>`); //16


8
文章作者: “秋了秋”个人博客,本站鼓励原创。
转载请注明本文地址:http://netblog.cn/blog/119.html
目录: 前端编程标签: 字符串文本统计 2599次阅读

请求播放音乐,请点击播放

登 录
点击获取验证码
还没账号?点击这里