find and replace string in javascript code example

Example 1: javascript replace

var res = str.replace("find", "replace");

Example 2: replace all occurrences of a string in javascript

const p = 'dog dog cat rat';

const regex = /dog/gi;

console.log(p.replace(regex, 'cow'));
//if pattern is regular expression all matches will be replaced
//output: "cow cow cat rat"

Example 3: how to use the replace method in javascript

let string = 'soandso, my name is soandso';

let replaced = string.replace(/soandso/gi, 'Dylan');

console.log(replaced); //Dylan, my name is Dylan

Example 4: 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 !"