我有这个字符串:
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>.
在有人告诉我为什么我不应该使用正则表达式来解析 HTML之前,我这样做的原因是因为这个字符串在网页上回显,括号和其中的文本有不同的颜色。我需要将它们包装在一个跨度中以便能够设置它们的样式。如果有更好的解决方案,我很开放。
非常感谢!