开发者

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

开发者 https://www.devze.com 2023-04-08 14:46 出处:网络
I\'m attempting to split a string by spaces into an array of words. If the string contains HTML tags, I would like the full tag (including content) to be treated as a single word.

I'm attempting to split a string by spaces into an array of words. If the string contains HTML tags, I would like the full tag (including content) to be treated as a single word.

For example,

I like to eat <a href="http://www.waffles.com/">tasty delicious waffles</a> 开发者_如何学运维for breakfast

should split into

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

I've seen a couple related threads on Stack Overflow but I'm having trouble adapting anything to Javascript because they were written for languages that I'm not quite familiar with. Is there a regex expression that could easily do this or will the solution require multiple regex splits and iteration?

Thanks.


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

will work if your tags can't be nested, if all tags are properly closed, and if current tag names don't occur in comments, strings etc.

Explanation:

<\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.


This is hard or impossible to do with regexp alone (depending on the complexity of HTML that you want/need to allow).

Instead, iterate over the children of the parent node and split them if they are text nodes or print them unmodified if they are non-text nodes.

0

精彩评论

暂无评论...
验证码 换一张
取 消