const str = 'A penny saved is a penny earned'; // "A dollar saved is a dollar earned" str.replace(/penny/g, 'dollar'); // "A dollar saved is a penny earned" - only replaces the first // instance by default. str.replace('penny', 'dollar');
replace(), you don't modify the original string.
String#replace() function has several special character sequences called "replacement patterns". Replacement patterns are useful when you want to replace all substrings that match a regular expression with a string that contains the match.
For example, suppose you wanted to add a
# before all numbers in a string. You can use the
$& replacement pattern, which inserts the matched substring.
const str = 'My favorite team is 1, everyone else is 2'; // "My favorite team is #1, everyone else is #2" str.replace(/\d+/g, '#$&');
More Fundamentals Tutorials