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.
Syntax of the replace() Method
Section titled “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
Section titled “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.
Argument 2: newValue
Section titled “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.
Below are some examples:
Example 1: Replace Friday with Sunday
Section titled “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
Section titled “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
Section titled “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
Section titled “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()’snewValueargument.
Let’s discuss the above points.
How to Use Special Replacement Patterns when replace()’s newValue Argument Is a String
Section titled “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"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
Section titled “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
Section titled “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>
Section titled “$<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
Section titled “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
Section titled “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
Section titled “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.
Let’s now discuss the syntax of the function argument.
Syntax of a replace() method’s function argument
Section titled “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";}As shown in the snippet above, replace()’s function argument accepts one or more parameters.
currentMatch
Section titled “currentMatch”The currentMatch parameter represents the matched pattern the computer is currently processing.
Example 1: Change code from lowercase to uppercase
Section titled “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-
Section titled “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
Section titled “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
Section titled “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
Section titled “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."Let’s now discuss the offset parameter.
offset
Section titled “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
Section titled “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
Section titled “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
Section titled “string”The string parameter is optional. It represents the entire calling string.
Example 1: Replace CodeSweetly
Section titled “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
Section titled “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
Section titled “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.
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!"