Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 based on the match.

Thanks.

like image 337
Tom Tucker Avatar asked Jan 26 '11 19:01

Tom Tucker


1 Answers

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

like image 143
ThiefMaster Avatar answered Sep 27 '22 00:09

ThiefMaster