簡體   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