The replace() method searches the given string for a specified value or a regular expression and returns a new string with some or all matched occurrences replaced.

The replace() method accepts two parameters:

const newStr = string.replace(substr|regexp, newSubstr|function)
  1. The first parameter can be a string or a regular expression. If it is a string value, only the first instance of the value will be replaced. To replace all occurrences of a specified value, you must use a regular expression with the global modifier (g).
  2. The second parameter can be a new string value or a function. If it is a function, it will be invoked after the match has been performed. The function's return value will be used as the replacement string.

The following example demonstrates how you can specify a replacement string as a parameter:

const str = "JavaScript Courses"
const newStr = str.replace('JavaScript', 'Java')

console.log(newStr) // Java Courses

To perform a global search to replace all occurrences of a string, you can use a regular expression with a global modifier:

const str = "Mr. Red owns a red bike and a red car."
const newStr = str.replace(/red/g, 'blue')

console.log(newStr)
// Mr. Red owns a blue bike and a blue car.

For a global case-insensitive replacement, you should combine the global modifier with the ignore case modifier:

const str = "Mr. Red owns a red bike and a red car."
const newStr = str.replace(/red/gi, 'blue')

console.log(newStr)
// Mr. blue owns a blue bike and a blue car.

Finally, you could also use a function as a second parameter to return the replacement text:

const str = 'Mr. Red owns a red bike and a red car.'
const newStr = str.replace(/red/gi, match => {
  return match.toUpperCase()
})

console.log(newStr)
// Mr. RED owns a RED bike and a RED car.

Read Next: How to use String replaceAll() method in JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.