Update:
It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b
)
'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"
This is a simple regex that avoids replacing parts of words in most cases. However, a dash -
is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat
:
'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"
basically, this question is the same as the question here:
Javascript replace " ' " with " '' "
@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!
var newText = "the cat looks like a cat".split('cat').join('dog');
Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:
var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
The output is the same as the accepted answer, however, using the /cat/g expression on this string:
var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??
Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:
var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"
My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.
http://www.javascriptkit.com/jsref/regexp.shtml
http://www.regular-expressions.info
Final addition:
Given that this question still gets a lot of views, I thought I might add an example of .replace
used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat
and cats
in one go:
'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
.replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
{
//check 1st, capitalize if required
var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
if (char1 === ' ' && char2 === 's')
{//replace plurals, too
cat = replacement + 's';
}
else
{//do not replace if dashes are matched
cat = char1 === '-' || char2 === '-' ? cat : replacement;
}
return char1 + cat + char2;//return replacement string
});
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
aba
inababa
withca
, which result do you expect?caba
?abca
?cca
? – reinierpostString.prototype.replaceAll()
is now a standard part of ECMAScript tc39.es/ecma262/#sec-string.prototype.replaceall, documented at developer.mozilla.org/docs/Web/JavaScript/Reference/… and shipped in Safari 13.1, Firefox 77 and Chrome Dev/Canary and will ship in Chrome 85. From the docs: “If searchValue is a string, replaces all occurrences of searchValue (as if.split(searchValue).join(replaceValue)
or a global & properly-escaped regular expression had been used). If searchValue is a non-global regular expression, throws an exception” – sideshowbarkerstr.replace(/abc/g, '');
so g to get all matches. – sarea