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?

3
  • 1
    str already equals 'banana boats or boat'. Commented Mar 24, 2018 at 17:13
  • Is your isse that only the first occurrence gets replaced using String-prototype.replace? Commented Mar 24, 2018 at 17:14
  • 1
    str.replace(new RegExp(toReplace, "g"), replacement) Commented Mar 24, 2018 at 17:14

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

if you like to replace more than one word, you could add a global flag 'g' as second parameter of the regex cosntructor.
1

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

new RegExp(toReplace, "g")

Comments

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"

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.