【问题标题】:Modify RegEx Match in JavaScript在 JavaScript 中修改 RegEx 匹配
【发布时间】:2011-01-26 19:54:55
【问题描述】:

我想在 JavaScript 中用方括号将给定字符串中出现的所有特定单词包装起来。

假设这些词是苹果、橙子和香蕉。那么主题文本"You are comparing apples to oranges."应该变成"You are comparing [apples] to [oranges]."

这个正则表达式是(apples|oranges),但问题是如何换行或更一般地,修改每个匹配项。 String.replace() 允许您将匹配项替换为某个预定义的值,而不是基于匹配项的值。

谢谢。

【问题讨论】:

  • 实际上,它的正则表达式是(apples|oranges)...

标签: javascript regex


【解决方案1】:
js> var str = 'You are comparing apples to oranges.';
js> str.replace(/(apples|oranges)/g, '[$1]')
You are comparing [apples] to [oranges].

如果您更喜欢一个可以简单地输入单词数组的函数:

function reg_quote(str, delimiter) {
    return (str+'').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\'+(delimiter || '')+'-]', 'g'), '\\$&');
}

function mark_words(str, words) {
    for(var i = 0; i < words.length; i++) {
        words[i] = reg_quote(words[i]);
    }
    return str.replace(new RegExp('(' + words.join('|') + ')', 'g'), '[$1]')
}

演示:

js> mark_words(str, ['apples', 'oranges']);
You are comparing [apples] to [oranges].
js> mark_words(str, ['apples', 'You', 'oranges']);
[You] are comparing [apples] to [oranges].

如果您希望它不区分大小写,请将'g' 替换为'gi'

【讨论】:

    【解决方案2】:

    除了其他人提到的简单替换字符串,您还可以将一个函数传递给String.replace(),每次匹配都会调用该函数,并将其返回值替换为结果字符串。这使您可以进行更复杂的转换。详情见:

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

    【讨论】:

      【解决方案3】:
      'You are comparing apples to oranges.'.replace(/(apples|oranges)/g, "[$1]");   
      //"You are comparing [apples] to [oranges]."
      

      【讨论】:

        【解决方案4】:

        这是一个非常丑陋的代码,但它可以完成工作:

            var string = "You are comparing apples to oranges";
            var regEx = "(apples|oranges)";
            var re = new RegExp(regEx, "g");
            for (var i=0; i<string.match(re).length; i++)
            {
                string = string.replace(string.match(re)[i], "[" + string.match(re)[i] + "]");
            }
            alert(string);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-10
          • 2012-02-22
          • 1970-01-01
          • 1970-01-01
          • 2010-09-10
          • 2015-12-10
          • 1970-01-01
          • 2020-03-06
          相关资源
          最近更新 更多