简体   繁体   English

我可以在迭代字符串时构建开始/结束标签吗?

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

I have a string that has some html tags in it.我有一个字符串,其中包含一些 html 标签。 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> .我希望能够在关闭</strong> <em>之前关闭第一个<em>并在关闭</strong>添加一个开头<em> </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?如果没有 DOMParser 或 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.您可以使用像(<.+?>)这样的正则表达式在 JavaScript 中找到开始和结束标记的位置,但考虑到 JavaScript 不支持正则表达式后视,您所要求的可能是不可能的,因为您将永远无法确定哪个结束标签与哪个开始标签相关。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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