replace() JavaScript String Method β How to Replace Text Strings
Whenever you use replace() on a string, the method does the following:
- It searches the string for a given pattern.
- It substitutes the pattern found with a new valueβthereby creating a new string.
- It returns the new version of the calling stringβwithout changing the original string.
- A calling string is a string on which you used
replace()
. So, in"Hello, world!".replace("world", "dear")
,"Hello, world!"
is the calling string. - Suppose the pattern you specified does not match any part of the calling string. In that case, the computer will return the calling string unaltered.
replace()
is sometimes written asString.prototype.replace()
because it is a method of theString
object'sprototype
property.
Syntax of the replace()
Methodβ
Here is replace()
's syntax:
callingString.replace(searchPattern, newValue);
The snippet above shows that replace()
accepts two arguments: a searchPattern and a newValue.
Argument 1: searchPattern
β
A searchPattern
is the first argument accepted by the replace()
method. It is used to specify the pattern you want to replace in the callingString
.
Keep in mind that you can use a string or a regular expression as the searchPattern
.
Suppose the searchPattern
argument is a string. In such a case, the computer will replace the first instance only.
To replace multiple instances of a pattern, use a regular expression with a g
(global) flag as the searchPattern
.
The computer will return the calling string unaltered if you omit the searchPattern
argument.
Argument 2: newValue
β
A newValue
is the second argument accepted by the replace()
method. It specifies the value you want to use to replace the searchPattern
found in the callingString
.
The computer will use undefined
as the newValue
if you do not provide a second argument.
Below are some examples:
Example 1: Replace Friday
with Sunday
β
"Friday, my friend, was born on Friday.".replace("Friday", "Sunday");
// The invocation above will return: "Sunday, my friend, was born on Friday."
The snippet above replaced only the first "Friday"
pattern of the calling string because we used a string as the searchPattern
. But you can also use a regular expression pattern for global replacement. Let's see an example below.
Example 2: Global Replacement of Friday
with Sunday
β
To replace all occurrences of a "Friday"
pattern, use a regular expression with a g
(global) flag like so:
"Friday, my friend, was born on Friday.".replace(/Friday/g, "Sunday");
// The invocation above will return: "Sunday, my friend, was born on Sunday."
Let's now see how to do a case-insensitive replacement.
Example 3: Global Case-Insensitive Replacement of walk
with Jogg
β
Whenever you need to do a case-insensitive replacement, add an i
(ignore case) flag to your regular expression like this:
const myText = "Walker walked into a shop while walking home.";
const myReplacementResult = myText.replace(/walk/gi, "Jogg");
console.log(myReplacementResult);
// The invocation above will return: "Jogger Jogged into a shop while Jogging home."
Important Stuff to Know about the replace()
Methodβ
Keep these two essential pieces of info in mind whenever you choose to use the replace()
method.
- If
replace()
's second argument is a string, you can include some special replacement patterns. - You can use a function as
replace()
'snewValue
argument.
Let's discuss the above points.
How to Use Special Replacement Patterns when replace()
's newValue
Argument Is a Stringβ
JavaScript has some special patterns that you can use if replace()
's second argument is a string. Let's talk about some of the special patterns below.
$$
Use $$
to insert a dollar sign.
Here's an example:
"David gave me 1.".replace(/1/, "$$80,000");
// The invocation above will return: "David gave me $80,000."
$&
β
Use $&
to reference the matched pattern.
Here's an example:
const string = "I love to code!";
string.replace("code", "$&...$&..., and $&");
// The invocation above will return: "I love to code...code..., and code!"
$`
β
Use $`
to reference the portion of the calling string that precedes the matched string.
Here's an example:
const string = "I love to code!";
string.replace("code", "sing, $`dance, and $`code");
// The invocation above will return: "I love to sing, I love to dance, and I love to code!"
$'
β
Use $'
to reference the portion of the calling string that succeeds the matched string.
Here's an example:
const string = "I love to code";
string.replace("to", "HTML$', CSS$', and JavaScript");
// The invocation above will return: "I love HTML code, CSS code, and JavaScript code"
$n
β
Use $n
to recall a captured group, where n
is the number that the computer assigned to the capturing group.
Example 1: Insert space between capturing groups 1 and 2β
const string = "CodingIsReallyFun";
string.replace(/([a-z])([A-Z])/g, "$1 $2");
// The invocation above will return: "Coding Is Really Fun"
Example 2: Swap patternsβ
const string = "50 Brown Tables";
string.replace(/(\d+)\s(\w+)\s(\w+)/g, "$2 $3 $1");
// The invocation above will return: "Brown Tables 50"
$<Name>
β
Use $<Name>
to recall a named captured group, where <Name>
is the name assigned to the capturing group.
Example 1: Insert space between the named capturing group 1 and 2β
const string = "CodingIsReallyFun";
string.replace(
/(?<lowerCaseLetter>[a-z])(?<upperCaseLetter>[A-Z])/g,
"$<lowerCaseLetter> $<upperCaseLetter>"
);
// The invocation above will return: "Coding Is Really Fun"
Example 2: Swap named patternsβ
const string = "50 Brown Tables";
string.replace(
/(?<number>\d+)\s(?<color>\w+)\s(?<item>\w+)/g,
"$<color> $<item> $<number>"
);
// The invocation above will return: "Brown Tables 50"
Let's now discuss using a function as replace()
's newValue
argument.
How to Use a Function as replace()
's newValue
Argumentβ
JavaScript allows you to use a function as replace()
's second argument.
If the newValue
argument is a function, the computer will do the following:
- It will invoke the function after each match.
- It will use the function's returned value to replace the pattern found.
Suppose the searchPattern
is a regular expression with a global flag. In such a case, the computer will invoke the function for each matched pattern.
In other words, JavaScript may run the function multiple times if the RegExp matches more than one pattern of the calling string.
Let's now discuss the syntax of the function argument.
Syntax of a replace()
method's function argumentβ
Here is the syntax of replace()
's function argument:
function createNewValue(currentMatch, p1,..., pX, offset, string, groups) {
return "newValue";
}
You can give the function any name or make it anonymous.
As shown in the snippet above, replace()
's function argument accepts one or more parameters.
currentMatch
β
The currentMatch
parameter represents the matched pattern the computer is currently processing.
You can give this parameter any name you desire.
Example 1: Change code
from lowercase to uppercaseβ
const string = "I love codesweetly!";
string.replace("code", function (currentMatch) {
return currentMatch.toUpperCase();
});
// The invocation above will return: "I love CODEsweetly!"
Example 2: Prepend walk
with Jogg-
β
const news = "Walker walked into a shop while walking home on a walkway.";
function setReplacement(currentMatch) {
return `Jogg-${currentMatch}`;
}
news.replace(/walk/gi, setReplacement);
// The invocation above will return:
// "Jogg-Walker Jogg-walked into a shop while Jogg-walking home on a Jogg-walkway."
Let's now discuss the p1, ..., pX
parameters.
p1, ..., pX
β
The p1, ..., pX
parameters are optional. They represent the pattern found by the nth capturing group of the searchPattern
argument.
Example 1: Replace Walk789
β
const news = "Walker walked into a shop while walking Walk789 home.";
function setNewValue(currMatch, p1) {
return `John, who has ${p1} dogs,`;
}
news.replace(/walk(\d+)/gi, setNewValue);
// The invocation above will return:
// "Walker walked into a shop while walking John, who has 789 dogs, home."
Example 2: Replace $1m shops
and Walk789
β
const news = "Walker walked into $1m shops while walking Walk789 home.";
function setNewValue(currMatch, p1, p2) {
return `John, who has ${p1 || p2} dogs,`;
}
news.replace(/(\W\d\w)\sshops|walk(\d+)/gi, setNewValue);
// The invocation above will return:
// "Walker walked into John, who has $1m dogs, while walking John, who has 789 dogs, home."
In the p1 || p2
logical statement, we used the OR operator (||
) to return the truthy operand.
Let's now discuss the offset
parameter.
offset
β
The offset
parameter is optional. It represents the offset position of the matched pattern within the entire calling string.
For instance, suppose the calling string is "Gorgeous"
, and the matched pattern is "geo"
. In that case, 3
will be the offset
parameter's value because "geo"
started from the 3rd index position.
Example 1: Replace daily
β
const string = "I drink water daily.";
string.replace("daily", function (currMatch, offset) {
return `${offset} times hourly`;
});
// The invocation above will return: "I drink water 14 times hourly."
Example 2: Replace 900xxxx
β
const news = "Walker walked into a shop while walking 900xxxx home.";
function setNewValue(currMatch, p1, offset) {
return `Mary, who has ${p1} Β£${offset}m dogs,`;
}
news.replace(/(\d+)x+/, setNewValue);
// The invocation above will return:
// "Walker walked into a shop while walking Mary, who has 900 Β£40m dogs, home."
Let's now discuss the string
parameter.
string
β
The string
parameter is optional. It represents the entire calling string.
Example 1: Replace CodeSweetly
β
const text = "I love CodeSweetly!";
text.replace("CodeSweetly", function (currMatch, offset, string) {
return `and ${string}`;
});
// The invocation above will return: "I love and I love CodeSweetly!!"
Example 2: Replace 7000 times
β
const text = "I eat fruits 7000 times";
function setNewValue(currMatch, p1, offset, string) {
return `and ${string} more than ${p1 * offset} people!`;
}
text.replace(/(\d+)\s\w+/, setNewValue);
// The invocation above will return:
// "I eat fruits and I eat fruits 7000 times more than 91000 people!"
Let's now discuss the groups
parameter.
groups
β
The groups
parameter is optional. It represents a collection of the named capturing groups you specified in the searchPattern
's regular expression. Or undefined
if the regular expression does not contain any named capturing group.
Some browser versions do not support named capturing groups.
Here's an example:
const text = "I eat fruits 7000 times";
function setNewValue(currMatch, p1, offset, string, groups) {
console.log(groups);
return `and ${string} more than ${
p1 * offset * groups.currentFruitRate
} people!`;
}
text.replace(/(?<currentFruitRate>\d+)\s\w+/, setNewValue);
// The invocation above will return:
// {currentFruitRate: "7000"}
// "I eat fruits and I eat fruits 7000 times more than 637000000 people!"
Overviewβ
replace()
returns a new version of its calling string after replacing some specified patterns with a given replacement.