.replace()
Returns a new string
with one, some, or all matches of a pattern replaced by a replacement
const paragraph = "I think Ruth's dog is cuter than your dog!"; console.log(paragraph.replace("Ruth's", 'my')); // Expected output: "I think my dog is cuter than your dog!" const regex = /Dog/i; console.log(paragraph.replace(regex, 'ferret')); // Expected output: "I think Ruth's ferret is cuter than your dog!"
.replaceAll()
Returns a new string with all matches of a pattern replaced by a replacement
string
or a RegExp
, and the replacement can be a string or a function to be called for each match.original string
is left unchanged.const paragraph = "I think Ruth's dog is cuter than your dog!"; console.log(paragraph.replaceAll('dog', 'monkey')); // Expected output: "I think Ruth's monkey is cuter than your monkey!" // Global flag required when calling replaceAll with regex const regex = /Dog/gi; console.log(paragraph.replaceAll(regex, 'ferret')); // Expected output: "I think Ruth's ferret is cuter than your ferret!"