Replacing words in a text while keeping the capitalization

I had to replace words in a text while keeping the capitalization in Javascript.

Given the text :
"It is a good burger. Or an hamburger. Burger is good".

With the replacement word "sandwich", it should become :
"It is a good sandwich. Or an hamburger. Sandwich is good".

It has 2 challenges :

  • Match only real words, e.g. match "burger", but not "hamburger"
  • Keep the capitalization of the word, e.g. "Burger" should become "Sandwich"

For the first one, we should use lookahead and lookbehind features of regular expressions, but unfortunately, in javascript there is no lookbehind, so we have to capture that part and return it with the result.

So here we go :
var replace = function(text, r, v) {
return text.replace(new RegExp('([^a-z])('+r+')|(^'+r+')(?=[^a-z]?)', "gi"), function(match, p1, p2, p3, offset, string) {
p1 = p1 || '';
p2 = p2 || p3;
if (p2[0].toUpperCase() == p2[0]) {
// Assume its all caps.
if (p2[1].toUpperCase() == p2[1]) {
v = v.toUpperCase();
}
// Assume its capitalized.
else {
v = v[0].toUpperCase() + v.slice(1);
}
}
return p1 + v;
});
}

Test it:
var text = "It is a good burger. Or an hamburger. Burger is good";
console.log(text + "\n" + replace(text, 'burger', 'sandwich'));