简体   繁体   English

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

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

I have a paragraph which has HTML tags in it. 我有一个段落,其中包含HTML标记。 I need to restrict it to 100 characters after the parse of HTML. 在解析HTML之后,我需要将其限制为100个字符。 For example 例如

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

If my length check is for 8, then my HTML should be Hello Wo where Wo should be an anchor tag. 如果我的长度检查是8,那么我的HTML应该是Hello Wo ,而Wo应该是锚标记。 There can be any other tags. 可以有任何其他标签。 Any help would be appreciated. 任何帮助,将不胜感激。

 $(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> 

Using this way you can create html elment virtually then text() will parse the text content from html. 使用这种方式,您可以虚拟地创建html元素,然后text()将解析html中的文本内容。

You can use a REGEX expresion when getting the innerHTML 获取innerHTML时可以使用REGEX表达式

Then count the characters. 然后计算字符。

Example: 例:

 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