Suppose I have string variable:
var animals = "catdog caT dog cat";
I don’t want cats, big caTs, and messy whitespaces. I’ve tried to use:
var rep = "cat"
var nocats = animals.replace(new RegExp(rep, 'g'), '');
and nocats is now “dog caT dog “, while I need “catdog dog”
What regexp should I use ?
I note that your question is not entirely clear on how exactly you would like whitespaces in the string to be treated. Assuming you want to collapse the whitespace in the source string, this should work:
Also make sure you are aware of the semantics of the word boundary assertion – “cat-dog” will be replaced to “-dog” in this case. An alternative will be
For reference: What is a word boundary in regexes?