繁体   English   中英

用空格分隔字符串(包含标签),而不会破坏标签或Javascript中的标签内部html

[英]Split a string (that contains tags) by spaces without breaking the tags or tag inner html in Javascript

我正在尝试通过空格将字符串拆分成单词数组。 如果字符串包含HTML标记,我希望将完整标记(包括内容)视为一个单词。

例如,

I like to eat <a href="http://www.waffles.com/">tasty delicious waffles</a> for breakfast

应该分成

I
like
to
eat
<a href="http://www.waffles.com/">tasty delicious waffles</a>
for
breakfast

我已经在Stack Overflow上看到了几个相关的线程,但是我很难适应Java脚本,因为它们是为我不太熟悉的语言编写的。 是否存在可以轻松做到这一点的正则表达式,或者解决方案是否需要多个正则表达式拆分和迭代?

谢谢。

result = subject.match(/<\s*(\w+\b)(?:(?!<\s*\/\s*\1\b)[\s\S])*<\s*\/\s*\1\s*>|\S+/g);

如果您的标签无法嵌套,所有标签均已正确关闭以及当前标签名称未出现在注释,字符串等中,则该标签将起作用。

说明:

<\s*            # Either match a < (+ optional whitespace)
(\w+\b)         # tag name
(?:             # Then match...
 (?!            # (as long as it's impossible to match...
  <\s*\/\s*\1\b # the closing tag here
 )              # End of negative lookahead)
 [\s\S]         # ...any character
)*              # zero or more times.
<\s*\/\s*\1\s*> # Then match the closing tag.
|               # OR:
\S+             # Match a run of non-whitespace characters.

仅凭正则表达式很难或不可能做到这一点(取决于您希望/需要允许的HTML的复杂性)。

取而代之的是,遍历父节点的子节点,如果它们是文本节点,则将其拆分;如果它们是非文本节点,则将它们未经修改地打印。

暂无
暂无

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

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