我有这个字符串:
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>.
在有人向我开枪之前 why shouldn't I use regex to parse HTML ,我这样做的原因是因为该字符串在网页上回显,并且括号和其中的文本具有不同的颜色。我需要将它们包裹在一个跨度中才能设计它们的样式。如果有更好的解决方案,我愿意。
非常感谢!
最佳答案
除了设置全局标志之外,您还需要使正则表达式变得懒惰:
var newString = oldString.replace(/\[(.*?)\]/g, "<span>[$1]</span>")
^ ^
关于javascript - 使用正则表达式和 JavaScript 将在字符串中多次出现的单个模式包装起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16902481/