【问题标题】:Replacing a word with another word zero or more times in javascript using regular expressions使用正则表达式在javascript中用另一个单词替换一个单词零次或多次
【发布时间】:2008-12-10 21:49:53
【问题描述】:

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

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

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

我瞄准的结果是:

这是一个带有一个的文本

但我得到的是:

这是一个带有一个

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

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

    wordReplaced = wordReplaced.replace(/\[lesserthen\]/g,"<");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      相关资源
      最近更新 更多