简体   繁体   中英

Can I build opening/closing tags while iterating over a string?

I have a string that has some html tags in it. I want to be able to find an opening and closing tag, and add those that are missing. For example, lets say I have this string:

Hello <strong>from <em>StackOverflow</strong> Hows it going</em>.

I want to be able to close the first <em> before the closing </strong> and add an opening <em> right after the closing </strong> . I will know what tags are included, but the stringI am provided could contain any variation of mixed up opening/closing tags.

How could I handle this without help from DOMParser or innerHTML?

Basically, I want to iterate the string and when I come across < , I want to start an opening string, and close it at > . Then, I want to start a closing tag when I come across </ and end it at > .

The problem is, when iterating a string, I will always start an opening tag due to checking one char at a time? How can I build these tags out of my string as I iterate?

You could find where both the opening and closing tags are in JavaScript with a regex like (<.+?>) , but considering regex lookbehind is unsupported in JavaScript, what you are asking is probably impossible, due to the fact that you'll never be able to work out which end tag correlates to which start tag.

Hope this helps!

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