JavaScript How to Replace Words in a String

Hi devs, today I'll show you how to replace word/words in a string. I'll show you two examples of replacing word/words in a string. So, let's see the examples.

Example 1: Replace a Single Word in a String

In the first example, we'll replace a single word in a string. For that we'll use replace() method of JavaScript Array. Let's see the below code snippet.

var str = "I Love medium.io Articles"; 
var resplacd_string = str.replace("medium.io", "shouts.dev");
console.log("Real sentence is = "+str);		
console.log("After Replacing the word, Real sentence is = "+resplacd_string);	

Which will produce the below output.

Usage of Replace Method

Example 2: Replace All Words in a String

In this example, we'll replace all matching words in a string. For that we'll use replaceAll() method of JavaScript Array. Let's see the below code snippet.

var str = "I Love medium.io Articles. But medium.io doesnt have too much JS Articles"; 
var resplacd_string = str.replaceAll("medium.io", "shouts.dev");
console.log("Real sentence is = "+str);		
console.log("After Replacing the word, Real sentence is = "+resplacd_string);	

Which will produce the below output.

Usage of ReplaceAll Method

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚