在JavaScript中修改RegEx匹配

时间:2011-01-26 19:54:56

标签: javascript regex

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

说这些话是苹果,橘子和香蕉。然后,主题文"You are comparing apples to oranges."应变为"You are comparing [apples] to [oranges]."

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

感谢。

4 个答案:

答案 0 :(得分:6)

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'

答案 1 :(得分:5)

除了其他人提到的简单替换字符串之外,您还可以将函数传递给为每个匹配调用的String.replace(),并将其返回值替换为结果字符串。这使您可以进行更复杂的转换。有关详细信息,请参阅:

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

答案 2 :(得分:2)

'You are comparing apples to oranges.'.replace(/(apples|oranges)/g, "[$1]");   
//"You are comparing [apples] to [oranges]."

答案 3 :(得分:1)

这是一个非常难看的代码,但是它完成了这项工作:

    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);