N.Car
N.Car

Reputation: 492

Replacing word in a string with another string - Javascript

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?

Upvotes: 0

Views: 140

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386766

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);

Upvotes: 2

surajs02
surajs02

Reputation: 471

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"

Upvotes: 1

Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel

Reputation: 114

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);

Upvotes: 0

brunnerh
brunnerh

Reputation: 185290

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

new RegExp(toReplace, "g")

Upvotes: 1

Related Questions