2

我有一个词 : [lesserthen],我需要<在一个字符串中用零次或多次替换。我正在使用该String.replace方法来做到这一点。但是这个词在字符串中只被替换了一次,我需要被替换不止一次。我对正则表达式很弱,我有兴趣找到解决这个问题的方法。

这是我一直在使用的代码:

var wordReplaced="This a text with one [lesserthen], and another [lesserthen]";
wordReplaced=wordReplaced.replace("[lesserthen]","<"):

我的目标是:

这是一个带有一个 < 和另一个 < 的文本

但我得到的是:

这是一个带有一个 < 和另一个 [lesserthen] 的文本

4

1 回答 1

5

尝试在替换中使用实际的正则表达式(带有“g”选项)而不是搜索字符串,例如:

wordReplaced = wordReplaced.replace(/\[lesserthen\]/g,"<");
于 2008-12-10T21:58:17.220 回答