How to replace word in a string - JavaScript

Mo Ibra

Mo Ibra

Dec 20, 2022

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.


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.


// String
const myString = "Hello World"

// Replace
const result = myString.replace("World", "John")

// Print Result:


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. 🚀

Suggestions For More Articles: