1var str = "JavaScript replace method test";
2var res = str.replace("test", "success");
3//res = Javscript replace method success
1const p = 'Dog dog';
2const regex = /Dog/gi;
3console.log(p.replace(regex, 'ferret'));
4// expected output: "ferret ferret"
5
1const search = 'duck'
2const replaceWith = 'goose';
3
4const result = 'duck duck go'.replaceAll(search, replaceWith);
5
6result; // => 'goose goose go'
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."
1function name(str,replaceWhat,replaceTo){
2 replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
3 var re = new RegExp(replaceWhat, 'g');
4 return str.replace(re,replaceTo);
5}