Introduction
Strings are everywhere in JavaScript, a sequence of characters that allows you to combine or make statements. With it (as an object) comes different operations that allow you to manipulate them. Though immutable, the language provides mediums and interfaces to play with strings. One such methods is the JavaScript's replace substring
method.
The replace()
method is a built-in function in JavaScript that is used to replace all occurrences of a specified substring within a string with another substring or value. The replace() method is commonly used in web development to manipulate text strings, such as modifying URLs, formatting user input, or sanitizing data. The replace()
method takes two parameters: the first parameter is the substring or regular expression to match, and the second parameter is the string or value to replace the matched substring with. If the first parameter is a regular expression, it can also include flags to modify the matching behavior. The replace()
method returns a new string with the replaced substring, leaving the original string unchanged.
In this article, we will explore the syntax, ways to use the replace()
method especially with regular expressions.
Syntax and Parameters of the replace()
Method
The syntax for the replace()
substring method is as follows:
string.replace(searchValue, replaceValue)
The method takes two parameters: searchValue
and replaceValue
.
searchValue
can be either a string or a regular expression, andreplaceValue
can be either a string or a function.
Using replace()
Method
To illustrate the possible approaches you can make in replacing substrings in JavaScript, here are some examples of how to use the replace()
substring method.
Replacing a Single Substring
The following example shows how to replace a single substring in a string:
let string = "Hello, User!";
let newString = string.replace("User", "Deepak");
console.log(newString);
Output
Hello, Deepak!
Replacing Multiple Substrings
The replace()
substring method can also replace multiple substrings in a string using regular expression flags - /g
. The following example shows how to replace multiple substrings in a string:
let string = "I love JavaScript and JavaScript loves me!";
let newString = string.replace(/JavaScript/g, "Go");
console.log(newString);
Output
I love Go and Go loves me!
In this example, we replace all occurrences of the substring "JavaScript" with "Go" using a regular expression with the g
flag, which stands for global.
Replacing with Regular Expressions
Regular expressions can be used as the first parameter of the replace()
method to perform more complex substitutions. Regular expressions are powerful patterns that can be used to match and replace text based on a set of rules.
Regular expressions can be used in the replace()
method by enclosing the pattern in forward slashes (/
). For example, /pattern/
would be a regular expression that matches the literal string "pattern".
Regular expressions can also include special characters and character classes that allow for more complex pattern matching. For example, the .
character in a regular expression matches any single character, and the *
character matches zero or more occurrences of the preceding character.
let string = "The price is $20.50";
let newString = string.replace(/\\$(\\d+)/, "€$1");
console.log(newString);
Output
The price is €20.50
In this example, we use a regular expression to match the substring "$20.50" and replace it with "€20.50". The regular expression /\\$(\\d+)/
matches a dollar sign followed by one or more digits and captures the digits using parentheses. The replacement string "€$1" uses the captured digits in the replacement.
Using Flags to modify the behavior of regular expressions
Flags can be used to modify the behavior of regular expressions in the replace()
method. Flags are appended to the regular expression pattern and control the matching behavior. The following flags are commonly used in the replace()
method:
g
: Global search, matches all occurrences of the pattern in the string.i
: Case-insensitive search, ignores the case of the letters in the pattern.m
: Multiline search, matches the pattern across multiple lines.
For example, to replace all occurrences of the substring "hello" in a case-insensitive manner, you can use the i
flag as follows:
let str = "Hello, hello, HELLO!";
let newStr = str.replace(/hello/gi, "hi");
console.log(newStr); // Output: "hi, hi, hi!"
Using Replacement patterns
Replacement patterns can be used in the replace()
method to create dynamic replacements based on the matched substring. Replacement patterns are special sequences that start with a dollar sign ($
) followed by a number or name, and are used to reference capture groups in the regular expression.
For example, to replace all occurrences of a date in the format "MM/DD/YYYY" with the format "YYYY-MM-DD", you can use the following regular expression:
let str = "Today is 04/20/2023";
let newStr = str.replace(/(\d{2})\/(\d{2})\/(\d{4})/g, "$3-$1-$2");
console.log(newStr); // Output: "Today is 2023-04-20"
In this example, the regular expression /(\d{2})\/(\d{2})\/(\d{4})/g
matches any date in the format "MM/DD/YYYY". The replacement string "$3-$1-$2"
puts the year first, followed by a dash, the month, another dash, and then the day.
Function as a replacement
A function can be used as the second parameter of the replace()
method to perform more complex replacements. The function is called for each match and returns the replacement value.
For example, to replace all occurrences of a substring with a capitalized version of the substring, you can use the following code:
let str = "the quick brown fox jumps over the lazy dog";
let newStr = str.replace(/\b\w/g, function(match) {
return match.toUpperCase();
});
console.log(newStr); // Output: "The Quick Brown Fox Jumps Over The Lazy Dog"
In this example, the regular expression /\b\w/g
matches the first letter of each word in the string. The function takes the matched letter as a parameter and returns the capitalized version of the letter. The replace()
method then replaces each matched letter with its capitalized version.
Summary
To summarize, the replace()
method is a built-in function in JavaScript that is used to replace all occurrences of a specified substring within a string with another substring or value. It takes two parameters: searchValue
and replaceValue
. The searchValue
parameter can be either a string or a regular expression, while the replaceValue
parameter is the string or value that will replace the matched substring(s).
Regular expressions can be used as the first parameter of the replace()
method to perform more complex substitutions. Flags can be used to modify the behavior of regular expressions in the replace()
method, while replacement patterns can be used to create dynamic replacements based on the matched substring.
In addition, a function can be used as the second parameter of the replace()
method to perform more complex replacements. This allows for more advanced string manipulations that are not possible with simple string replacement.
References
String.prototype.replace() - JavaScript | MDN (mozilla.org)