JavaScript String Replace

In this post, we'll learn how to use JavaScript's replace method on the String prototype.
The most common use case for this method is to replace a string with another string.
Here's an example of using replace
to replace a string with another one:
let string = "Hello World";
let newString = string.replace("World", "Universe");
console.log(newString); // Hello Universe
Because the replace()
method returns the new string, you can chain them together:
let string = "Hello World";
let newString = string.replace("World", "Universe").replace("Hello", "Goodbye");
console.log(newString); // Goodbye Universe
This works because in JavaScript, strings are immutable, so every time you want a different string, a new one has to be created.
The replace()
method supports more than just plain strings.
You can use $& to reference the match itself.
let string = "Hello World";
let newString = string.replace("World", "$& $&");
console.log(newString); // Hello World World
You can use $` to reference the string before the match.
let string = "Hello World";
let newString = string.replace("World", "$`");
console.log(newString); // Hello Hello
You can use $' to reference the string after the match.
let string = "Hello World";
let newString = string.replace("World", "$'");
console.log(newString); // Hello
Regular Expressions
While plain-text strings are easy to work with, sometimes we need something a little more powerful.
Thankfully, the replace()
method supports regular expressions.
Simply pass in your regular expression as the first argument, and the string to replace it with as the second argument.
let string = "Hello World";
let newString = string.replace(/World/g, "Universe");
console.log(newString); // Hello Universe
Replacer Functions
You can use a function, known as the replacer function, as the second argument to replace()
.
This function will be called for every match, allowing you to modify the string as you see fit.
Here's an example of using a replacer function:
let string = "Hello World";
let newString = string.replace(/World/g, match => {
return match.toUpperCase();
});
console.log(newString); // Hello WORLD
You can also take advantage of different groups in your regular expression.
let string = "Hello World";
let newString = string.replace(/(\w+) (\w+)/g, (match, p1, p2) => {
return `${p1}+${p2}`;
});
console.log(newString); // Hello+World
Conclusion
We've seen how to use the replace()
method on the String prototype to replace a string with another one. We've also seen how to use regular expressions and replacer functions for even more powerful string replacements.
Hopefully this post has been helpful to you!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!