Published Feb 11 2019
Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨
Finds the first occurrence of str1
in the current string and replaces it with str2
.
Returns a new string without mutating the original one.
'JavaScript'.replace('Java', 'Type') //'TypeScript'
You can pass a regular expression as the first argument:
'JavaScript'.replace(/Java/, 'Type') //'TypeScript'
replace()
will only replace the first occurrence, unless you use a regex as the search string, and you specify the global (/g
) option:
'JavaScript JavaX'.replace(/Java/g, 'Type') //'TypeScript TypeX'
The second parameter can be a function. This function will be invoked when the match is found (or for every match foundm if using a global regex /g
), with a number of arguments:
The return value of the function will replace the matched part of the string.
Example:
'JavaScript'.replace(/Java/, (match, index, originalString) => {
console.log(match, index, originalString)
return 'Test'
}) //TestScript
This also works for regular strings, not just regexes:
'JavaScript'.replace('Java', (match, index, originalString) => {
console.log(match, index, originalString)
return 'Test'
}) //TestScript
In case your regex has capturing groups, those values will be passed as arguments right after the match parameter:
'2015-01-02'.replace(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/, (match, year, month, day, index, originalString) => {
console.log(match, year, month, day, index, originalString)
return 'Test'
}) //Test