0

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 ?

jwaliszko
  • 16,942
  • 22
  • 92
  • 158

2 Answers2

2

Use \b for word boundary and case insensitive (i flag) regex:

var animals = "catdog caT dog cat",
    animal = "cat"


animals.replace(new RegExp("\\b" + animal + "\\b", "gi"), "");
// "catdog  dog " needs additional trimming
Esailija
  • 138,174
  • 23
  • 272
  • 326
0

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:

// " catdog      caT  dog    cat" --> "catdog dog" 
animals.replace(new RegExp('\\s*\\b' + animal + '\\b\\s*|\\s+', 'gi'), ' ').trim();

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

// " cat_dog cat-dog cat dog catdog catcatdog " --> "cat_dog cat-dog dog catcatdog" 
animals.replace(new RegExp('(^|\\s+)' + animal + '(\\s+|$)|\\s+', 'gi'), ' ').trim();

For reference: What is a word boundary in regexes?

Community
  • 1
  • 1
staafl
  • 3,147
  • 1
  • 28
  • 23