0

Does anyone know any regex expression where I can replace a word found in a string with another string?

var replacement = "car";
var toReplace = "boat";
var str = "banana boats or boat"
str = str.replace(toReplace, replacement);

I want str to be equals to "banana boats or car" instead of "banana cars or car"

Any suggestions?

Salman A
  • 262,204
  • 82
  • 430
  • 521
N.Car
  • 492
  • 1
  • 4
  • 14

4 Answers4

2

You could use a word boundary \b for replacing only the whole word, not parts of a word in a new created regular expression with the wanted word.

var replacement = "car",
    toReplace = "boat",
    str = "banana boats or boat";
    
str = str.replace(new RegExp('\\b' + toReplace + '\\b', 'g'), replacement);

console.log(str);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • if you like to replace more than one word, you could add a global flag `'g'` as second parameter of the regex cosntructor. – Nina Scholz Mar 24 '18 at 17:50
1

You need the global flag for multiple matches. So pass this as the replacement regex:

new RegExp(toReplace, "g")
H.B.
  • 166,899
  • 29
  • 327
  • 400
1

The replace only replaces the first instance of the search string toReplace in str.

To replace all instances of toReplace in str, use a RegEx object and the g (global) flag with toReplace as the search string:

var replacement = "car";
var toReplace = "boat";
var str = "banana boats or boat";

var toReplaceRegex = new RegExp(toReplace, "g");
str = str.replace(toReplaceRegex, replacement); 
console.log(str); // prints "banana cars or car"
surajs02
  • 451
  • 7
  • 18
0

Your question is unclear because str already equals "banana boats or boat" by default before you changed it! ...but you can do this if you insist

var replacement = "car"; 
var toReplace = "boat"; 
var str = "banana boats or boat" 
str = str.replace(replacement, toReplace);