1var str = "JavaScript replace method test";
2var res = str.replace("test", "success");
3//res = Javscript replace method success
1function replaceAll(str, find, replace) {
2 var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
3 return str.replace(new RegExp(escapedFind, 'g'), replace);
4}
5//usage example
6var sentence="How many shots did Bill take last night? That Bill is so crazy!";
7var blameSusan=replaceAll(sentence,"Bill","Susan");
1let string = 'soandso, my name is soandso';
2
3let replaced = string.replace(/soandso/gi, 'Dylan');
4
5console.log(replaced); //Dylan, my name is Dylan
1let re = /apples/gi;
2let str = "Apples are round, and apples are juicy.";
3let newstr = str.replace(re, "oranges");
4console.log(newstr)
5
6output:
7
8"oranges are round, and oranges are juicy."
1const p = 'Its going to rain today and its going to rain tomorrow';
2
3// Example of replacing all occurrances
4
5// g = global search, which searches all instances
6// i = case insensitive, which will match 'a' with 'A'
7const regex = /rain/gi;
8console.log(p.replace(regex, 'snow'));
9// expected output: "Its going to snow today and its going to snow tomorrow"
10
11// Example of replacing the first occurance
12console.log(p.replace('rain', 'snow'));
13// expected output: "Its going to snow today and its going to rain tomorrow"
14