簡體   English   中英

使用Regex和JavaScript將單個模式多次出現在字符串中

[英]Wrap single pattern occurring more than one time in a string using Regex and JavaScript

我有這個字符串:

whatever [that's the pattern] by [pattern again] before [whatever].

我希望將方括號[]包裹起來,然后將其全部包裹起來,就像這樣:

whatever <span>[that's the pattern]</span> by </span>[pattern again]</span>
before <span>[whatever]</span>.

我努力了

re = new RegExp(/\[(.*)\]/);
var newString =  oldString.replace(re, "<span>$1</span>");

但這返回:

whatever <span>[that's the pattern] by [pattern again] before [whatever]</span>.

在有人問我為什么不應該使用regex解析HTML之前 ,我這樣做是因為在Web頁上回顯了此字符串,並且括號和其中的文本具有不同的顏色。 我需要將它們包起來才能對其進行樣式設置。 如果有更好的解決方案,我會開放。

非常感謝!

除了設置全局標志之外,還需要使正則表達式變得懶惰:

var newString = oldString.replace(/\[(.*?)\]/g, "<span>[$1]</span>")
                                        ^    ^

您需要設置全局標志,它告訴它匹配多次:

oldString.replace(/\[(.*)\]/g, ...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM