开发者

Modify RegEx Match in JavaScript

I want to wrap all occurrences of certain words in a given string with square brackets in JavaScript.

Say these words are apples, oranges, and bananas. Then a subject text "You are comparing apples to oranges." should turn into "You are comparing [apples] to [oranges]."

The regular expression for this would be (apples|oranges), but the question is how to wrap or more generally, modify each match. String.replace() lets you replace matches founds with some pre-defined value, rather a value bas开发者_StackOverflow社区ed on the match.

Thanks.


js> var str = 'You are comparing apples to oranges.';
js> str.replace(/(apples|oranges)/g, '[$1]')
You are comparing [apples] to [oranges].

If you prefer a function where you can simply feed an array of words:

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]')
}

Demo:

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].

If you want it case insensitive, replace 'g' with 'gi'.


In addition to the simple substitution string mentioned by others, you can also pass a function to String.replace() which is called for each match, and whose return value is substituted into the resulting string. This lets you do more complicated transformations. For details, see:

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


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


This is a very ugly code, but it does the job:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜