JavaScript String replace() is a built-in method that returns a new string by replacing some or all parts of an existing string that match a specified pattern (string or RegExp) with a replacement value (string).
let input = "Today is a Saturday, I love Saturday"; let output = input.replace("Saturday", "Sunday") console.log(output); // Output: Today is a Sunday, I love Saturday
In this code, only the first “Saturday” is replaced by “Sunday” because string patterns replace only the first match; subsequent matches (if any) are ignored. It does not modify the original string since it is immutable.
Syntax
string.replace(search_value, new_value)
Parameters
Argument | Description |
search_value (required) |
It represents a value to search for. If it is a string, it matches and replaces only the first occurrence (case-sensitive). If it is a RexExp object, it enables advanced pattern matching. If not a RegExp or custom object, it is coerced to a string. |
new_value (required) | It is the value to insert in place of the match(es).
It can be a string or a function. |
Replace using Regular Expressions
If you don’t know the specific string but you know the pattern of it, you can use regular expressions to target that pattern and replace it.
Matching an exact substring is good, but we often need to match a pattern instead. It can quickly be done using the regular expression as the first argument.
const text = "cat dog tiger"; console.log(text.replace(/cat/, "cow")); // Output: "cow dog tiger"
RegExp with global flag (All Matches)
If you want to replace all occurrences, pass the “g” flag to the Regular Expression.
const text = "cat dog cat cat tiger"; console.log(text.replace(/cat/g, "cow")); // Output: cow dog cow cow tiger
The above program shows that it replaced all the “cat” strings with “cow” strings.
Case-Insensitive replacement
By default, the replace() method is case-sensitive. Meaning, it treats “Web” and “web” strings differently.
const text = "Apple apple"; console.log(text.replace(/apple/g, "orange")); // Output: Apple orange
Even after using global replacement, it does not replace “Apple” because it is case-sensitive.
To replace a specific string regardless of its case sensitivity, pass the “i” argument while passing a RegExp.
const text = "Apple apple"; console.log(text.replace(/apple/gi, "orange")); // Output: orange orange
In the above code, we passed “/gi”, where “g” stands for global and “i” stands for ignore cases.
Replacement string with special patterns
const str = "Price: $100"; const result = str.replace(/\$(\d+)/, "USD $1"); console.log(result); // Output: Price: USD 100
Here $1 refers to the first captured group (\d+).
Capturing Groups with $n
Let’s capture two grouped characters “te” ($1) and “st” ($2), and swap them.
const str = "test"; const result = str.replace(/(te)(st)/, "$2$1"); console.log(result); // Output: Price: stte
In this program, we swapped the substrings of the “test” string. The first “te” and last “st” have been swapped, and the final string is “stte”.
Function as a Replacement
We can pass a replacement value as a function like this:
const str = "aabbcc" const output_str = str.replace(/./g, (match) => match.toUpperCase()) console.log(output_str); // Output: AABBCC
In this code, we pass a function as a value, which is called for each match (due to g), uppercasing characters.
Replacing an array of strings
What if we have an array of strings and we want to replace the string value of a specific element?
In that case, we need to go through each element one by one using an array.map() method. Once we find an element that needs to be replaced, we will use the string.replace() method and replace that specific element’s value with the provided value, transform, and return the array.
let ingredients = ['Y-MEN', 'Avengers', 'Loki']; ingredients = ingredients.map(ingredient => { return ingredient.replace('Avengers', 'Revengers'); }); console.log(ingredients); // Output: ['Y-MEN', 'Revengers', 'Loki']
That’s all!