簡體   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