简体   繁体   中英

Javascript: Length of string without HTML tags

I have a text containing HTML and my own special mark-up. 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 /> '

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:

text.match( /(\[.*?\])/g)

g modifier refers to 'global', which means, find all matches, not just the fist one.

Use:

document.querySelector('.your_element').innerHTML.length;

The innerHTML method strip the HTML tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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