Definition and Usage
The replace()
function for strings searches for a specific part of a string and replaces it with another string.
Features
- Uses a specific substring or a regular expression pattern to search within the original string,
- The matched portion is replaced with the desired string and returned.
- By default, only the first match is replaced, but if you use a
g
flag in the regular expression pattern, all matches can be replaced. - The original string remains unchanged.
Basic Example
const str = "I like yellow the most~";
const replacedStr = str.replace("yellow", "blue");
console.log(replacedStr); // "I like blue the most~"
Syntax
str.replace(searchValue, newValue);
str
is the string to which the replace()
function is applied.
Parameters
searchValue |
Specifies what to search for in the string to be replaced.
You can provide either a specific substring or a regular expression pattern. |
---|---|
newValue |
Specifies the new string to replace the matched value.
You can provide either a string or a function that returns the replacement string.
|
Return Value
Returns a new string where the searchValue
has been replaced with newValue
.
The original string is not modified.
searchValue
: How to Specify the Value to Replace
You can provide either a specific substring or a regular expression pattern to search for the target text.
Searching with a Specific Substring
When searching with a specific substring, only the first match found is replaced.
const originalString = "Hello, JavaScript! JavaScript!";
const newString = originalString.replace("JavaScript", "JS");
// The matched portion is replaced with the desired string.
// Only the first occurrence is replaced.
console.log(newString); // Output: "Hello, JS! JavaScript!"
// The original string is not modified.
console.log(originalString); // Output: "Hello, JavaScript! JavaScript!"
Searching with a Regular Expression Pattern
const originalString = "I am 20 years old.";
const newString = originalString.replace(/\d+/, "**");
// \d+ matches one or more digits
// The matched portion is replaced with the desired string.
console.log(newString); // Output: "I am ** years old."
// The original string is not modified.
console.log(originalString); // Output: "I am 20 years old."
Regular expression patterns also replace only the first match by default. However, if you use a pattern with the g
flag, all matches can be replaced.
The g
flag stands for "global," meaning it searches for all occurrences of the pattern within the string and replaces them.
const text = "apple banana apple";
// Using the g flag
const result = text.replace(/apple/g, "orange");
console.log(result); // Output: "orange banana orange"
// Without the g flag
const resultNotG = text.replace(/apple/, "orange");
console.log(resultNotG); // Output: "orange banana apple"
In the code above, using the /apple/g
regular expression with the g
flag replaces all occurrences of "apple" with "orange" in the string.
newValue
: How to Specify the Replacement
You can provide either a string or a function that returns the replacement when searchValue
is matched.
Providing a String
If you provide a string, the matched portion is replaced with the specified string.
newValue
const originalString = "Hello, JavaScript!";
const newString = originalString.replace("JavaScript", "JS");
console.log(newString); // Output: "Hello, JS!"
Providing a Function
If you provide a function, it is called for each match, and its return value is used as the replacement string.
newValue
const originalString = "Hello, JavaScript!";
const newString = originalString.replace("JavaScript", function(match) {
// match is the entire substring found by replace()
return match.toUpperCase();
});
console.log(newString); // Output: "Hello, JAVASCRIPT!"
Here, match
represents the entire substring found by replace()
, and toUpperCase()
is used to convert it to uppercase before returning.
Providing a Function
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
return replacement;
}
Each parameter has the following meaning:
match |
The entire matched substring. |
---|---|
p1, p2, ..., pN |
The substrings corresponding to each capturing group in the regular expression. |
offset |
The index of the match within the original string. |
string |
The original string. |
groups |
An object containing named capturing groups (only exists if the regular expression contains named groups, e.g., /(a)(?<b>c)/ ). |
The function should return the replacement value, which replace()
uses. Using a function as newValue
allows you to implement dynamic replacement logic for matched substrings.
Example: Formatting a Phone Number
// Example: formatting a phone number
const phoneNumber = "123-456-7890";
const re = /(\d{3})-(\d{3})-(\d{4})/;
// (\d{3}): first group, area code
// (\d{3}): second group, prefix
// (\d{4}): third group, line number
const formattedNumber = phoneNumber.replace(re, function(match, areaCode, prefix, lineNumber) {
// match: entire matched substring (e.g., "123-456-7890")
// areaCode: first group (e.g., "123")
// prefix: second group (e.g., "456")
// lineNumber: third group (e.g., "7890")
return `+1 (${areaCode}) ${prefix}-${lineNumber}`;
});
console.log(formattedNumber);
// Output: "+1 (123) 456-7890"
In this example, the regular expression (\d{3})-(\d{3})-(\d{4})
groups the phone number parts. The callback function then uses these groups to format the number in a new style. As a result, "123-456-7890" is replaced with "+1 (123) 456-7890".
Note:
Regular expressions are powerful and flexible for searching and transforming strings, but their syntax can be abstract and challenging for beginners. Complex patterns or metacharacters may be confusing at first. Take your time and use documentation or tutorials to gradually understand them.
Practical Examples
The replace()
function can be useful in a variety of situations. Here are some examples:
Masking Part of an Email Address
const email = "john.doe@example.com";
const hiddenEmail = email.replace(/(?<=.{3})[^@](?=[^@]*@)/g, "*");
console.log(hiddenEmail);
// Output: "joh*************@example.com"
In this example, all characters except for the first three in the email address are replaced with asterisks (*
).
The regular expression (?<=.{3})
matches the position after the first three characters, and (?=[^@]*@)
matches the position before the @
symbol.
Removing HTML Tags
const htmlString = "<p>Hello, <strong>world</strong>!</p>";
const plainText = htmlString.replace(/<[^>]*>/g, "");
console.log(plainText);
// Output: "Hello, world!"
This example removes all HTML tags from a string, leaving only the plain text. The regular expression <[^>]*>
matches any sequence that starts with <
and ends with >
, and replaces it with an empty string.
Replacing Words
const sentence = "JavaScript is fun!";
const replacedSentence = sentence.replace("JavaScript", "TypeScript");
console.log(replacedSentence);
// Output: "TypeScript is fun!"
This example performs a simple word replacement. Using the replace()
function, "JavaScript" is replaced with "TypeScript," resulting in the new sentence "TypeScript is fun!". Such straightforward replacements are commonly used in everyday string manipulation tasks.
Compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
---|---|---|---|---|---|
replace()
|
1 | 12 | 1 | 1 | 0.10 |
Specifications
Specification | |
---|---|
String.prototype.replace()
|
ECMAScript® 2026 Language Specification #sec-string.prototype.replace |