javascript replace and retrieve string code example

Example 1: replace in string javascript

const p = 'hello world ! hello everyone ! ';

const regex = /hello/gi;

console.log(p.replace(regex, 'good morning'));
// expected output: "good morning world ! good morning everyone !"

console.log(p.replace('hello', 'good evening'));
// expected output: "good evening world ! hello everyone !"

Example 2: replace() in javascript

replace(regexp, newSubstr)
replace(regexp, replacerFunction)

replace(substr, newSubstr)
replace(substr, replacerFunction)