1var myStr = 'this,is,a,test';
2var newStr = myStr.replace(/,/g, '-');
3
4console.log( newStr ); // "this-is-a-test"
1var str = "JavaScript replace method test";
2var res = str.replace("test", "success");
3//res = Javscript replace method success
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."
1var str = "Please locate where 'locate' occurs!";
2
3str.replace("locate", "W3Schools"); //replace only replace first match from string
4str.replace(/LOCATE/i, "W3Schools"); // i makes it case insensitive
5str.replace(/LOCATE/g, "W3Schools"); // g replace all matches from string rather than replacing only first
6