JavaScript Program to Replace All Occurrences of a String

replace() method returns a new string with the specified string replaced. Let’s see an example. Syntax of replace function is given below.

Syntax :

string.replace(pattern, replacement)

const message = "abc xyz";

// replace the first b with c
let result = message.replace('b', 'c');

//Output: acc xyz        

We can replace also the first occurrence in the string. Let’s see an example.

const str = "Java is awesome"

let pattern = "Java";
let new_str = str.replace(pattern, "JavaScript");


// Output: JavaScript is awesome        

We can replace all occurrences. Let’s see an example.

const str = "Java is awesome. Java is popular"
let pattern = "Java";
let new_str = str.replaceAll(pattern, "JavaScript");

// Output: "JavaScript is awesome. JavaScript is popular"        
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top