Skip to content

The String replace() method

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
→ 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: