Skip to content

The String replace() method

New Course Coming Soon:

Get Really Good at Git

Find out all about the JavaScript replace() method of a string

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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: