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.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With