How to replace part of a string with another string in JavaScript?

June 13, 2020 - 1 min read

We can use the replace string method to replace a string with another string in JavaScript.

Consider this string.

const greeting = "Hi, Friend";

Let's replace the string Hi to Hello.

const greeting = "Hi, Friend";

// replacing string Hi to Hello
greeting.replace("Hi", "Hello"); // Result: Hello, friend
  • The method accepts the string to replace as the first argument.
  • And the string to be replaced with as the second argument.
  • It returns a string with the replaced string.
  • The method also accepts Regular expression as the first argument.
  • It is a string only method.

Using regular expression

We can also replace all the occurrences of a specific word in a string using a regular expression.

const favoriteLine = "Blue has 3 Blue bottles";

// all occurences of Blue will be replaced by Green
str.replace(/blue/gi, "Green"); // Result: Green has 3 Green bottles

Feel free to share if you found this useful 😃.