[英]Javascript: Length of string without HTML tags
I have a text containing HTML and my own special mark-up. 我有一个包含HTML和我自己的特殊标记的文本。 Before I print the text, I need to know its length, so I can generate apropriate speech bubble.
在我打印文本之前,我需要知道它的长度,所以我可以产生适当的语音泡沫。
I am trying to get the actual length of the string, but I am unable to get length of all special mark-ups. 我试图获得字符串的实际长度,但我无法获得所有特殊标记的长度。
He're an example of the string 他是这个字符串的一个例子
var text = 'Lorem ipsum dolor sit amet [T1]. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquam accumsan elit, non vestibulum ex venenatis vitae. <br /><br />[D|1000] Hesitulus <br /> <span class="important"> l[D|100]o[D|100]r[D|100]e[D|100]m</span> <br />
var text = 'Lorem ipsum dolor sit amet [T1]. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquam accumsan elit, non vestibulum ex venenatis vitae. <br /><br />[D|1000] Hesitulus <br /> <span class="important"> l[D|100]o[D|100]r[D|100]e[D|100]m</span> <br />
' var text = 'Lorem ipsum dolor sit amet [T1]. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquam accumsan elit, non vestibulum ex venenatis vitae. <br /><br />[D|1000] Hesitulus <br /> <span class="important"> l[D|100]o[D|100]r[D|100]e[D|100]m</span> <br />
'
I am trying to get the length of all "[]"-type substrings using a regexp, but I am no master of that and I fail only having the first one. 我试图使用正则表达式获取所有“[]” - 类型子串的长度,但我不是那个的主人,我只失败了第一个。 Tried few more options, but with no success.
尝试了几个选项,但没有成功。
var allMyMarkup = text.match( /(\[.*?\])/); // selecting only the first code
How to get all occurences of my pattern? 如何获得我的模式的所有出现?
Use 'g' modifier like below: 使用如下所示的'g'修饰符:
text.match( /(\[.*?\])/g)
g modifier refers to 'global', which means, find all matches, not just the fist one. g modifier指的是'global',这意味着,找到所有匹配,而不仅仅是第一个匹配。
Use: 采用:
document.querySelector('.your_element').innerHTML.length;
The innerHTML method strip the HTML tags. innerHTML方法剥离HTML标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.