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');
console.log(result);
//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");
console.log(new_str);
// 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");
console.log(new_str);
// Output: "JavaScript is awesome. JavaScript is popular"