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"
console.log(p.replace('dog', 'cow'));
// If pattern is a string, only the first occurrence will be replaced.
//output: "cow dog cat rat"
How to Use the replace() String Method in javascript
// use a regex in place of a string as a replacer
const string = "Hello world"
const modified = string.replace(/o/g, "--")
console.log(string)
// Hello world
console.log(modified)
// Hell-- w--rld
var str = "Please locate where 'locate' occurs!";
str.replace("locate", "W3Schools"); //replace only replace first match from string
str.replace(/LOCATE/i, "W3Schools"); // i makes it case insensitive
str.replace(/LOCATE/g, "W3Schools"); // g replace all matches from string rather than replacing only first
const p = 'Its going to rain today and its going to rain tomorrow';
// Example of replacing all occurrances
// g = global search, which searches all instances
// i = case insensitive, which will match 'a' with 'A'
const regex = /rain/gi;
console.log(p.replace(regex, 'snow'));
// expected output: "Its going to snow today and its going to snow tomorrow"
// Example of replacing the first occurance
console.log(p.replace('rain', 'snow'));
// expected output: "Its going to snow today and its going to rain tomorrow"
//Replace the first match in a string
//If you wish to replace all matches, use the replaceAll() method.
var str = "JavaScript replace method test";
var res = str.replace("test", "success");
//res = Javscript replace method success
var frase = "Son tres mil trescientos treinta y tres con nueve";
frase = frase.replace("tres","dos");
console.log(frase);
//Son dos mil trescientos treinta y tres con nueve
let str = "I like to eat, eat, eat apples and bananas";
let re = /apples|bananas/gi;
let newStr = str.replace(re, (match) => {
console.log({match});
return match.toUpperCase();
});
console.log(newStr);
Code language: JavaScript (javascript)