繁体   English   中英

查找字符串长度而不计算包含的html标签

[英]Find length of string without counting included html tags

我有一个段落,其中包含HTML标记。 在解析HTML之后,我需要将其限制为100个字符。 例如

Hello<a href ="#"> World </a>

如果我的长度检查是8,那么我的HTML应该是Hello Wo ,而Wo应该是锚标记。 可以有任何其他标签。 任何帮助,将不胜感激。

 $(document).ready(function(){ var $html=$('<span></span>'); $html.append('Hello<a href ="#"> World </a>'); var text=$html.text(); console.log("Text :: "+text); console.log("Length :: "+text.length); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用这种方式,您可以虚拟地创建html元素,然后text()将解析html中的文本内容。

获取innerHTML时可以使用REGEX表达式

然后计算字符。

例:

 var regex = /(<([^>]+)>)/ig; var body = 'Hello<a href ="#"> World </a>'; var result = body.replace(regex, ""); console.log(result + ' ' + result.length); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM