In this article we will learn how to replace word in a string.
It is very common to replace word in a string in JavaScript.
Problem
Now we have a problem, which is that we want to replace one word with another word in the string in JavaScript.
Imagine you have a string like this:
"Hello World"
And you want to replace "World" with "John"
How to solve this problem?
Well, the solution to this problem is easy, especially with a function like replace
Replace word in string with replace
method
We can use replace()
method to replace word in string.
Example
// String
const myString = "Hello World"
// Replace
const result = myString.replace("World", "John")
// Print Result:
console.log(result);
Output
Hello John
The replace()
method returns a new string with one, some, or all matches of a pattern replaced by a replacement.
Thank you for reading
Thank you for reading my blog. 🚀