How to use String replace() method in JavaScript

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')

// 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')

// 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()

// 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.