我试图用空格将字符串拆分成一个单词数组。如果字符串包含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上看到了几个相关的线程,但是我无法适应Javascript,因为它们是针对我不太熟悉的语言编写的。是否存在可以轻松执行此操作的正则表达式,或者解决方案是否需要多个正则表达式拆分和迭代?
感谢。
答案 0 :(得分:6)
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.
答案 1 :(得分:1)
单独使用regexp很难或不可能(取决于您希望/需要允许的HTML的复杂性)。
相反,迭代父节点的子节点并在它们是文本节点时将它们拆分,或者如果它们是非文本节点则不加修改地打印它们。