# How to use String replace() method in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 9, 2021, updated Oct 23, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-string-replace

> A quick introduction to the JavaScript string replace() and replaceAll() methods and how to use them to replace a text in a string. 

The `replace()` method searches the given string for a specified value or a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions) and returns a new string with some or all matched occurrences replaced.

The `replace()` method accepts two parameters:

```javascript
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](https://attacomsian.com/blog/javascript-regular-expressions#regular-expression-modifiers) (`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:

```javascript
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](https://attacomsian.com/blog/javascript-regular-expressions#regular-expression-modifiers) with a global modifier:

```javascript
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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/javascript-string-replaceall)
