简体   繁体   中英

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

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.

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