5

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.

1
  • 2
    Actually, the regexp for that would be (apples|oranges)... Commented Jan 26, 2011 at 20:04

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.