We can use the
Consider this string.
const greeting = "Hi, Friend";
Let's replace the string
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