JavaScript replace() method
The replace()
method in JavaScript is used to search for a specified substring or pattern in a string and replace it with a new substring. This method is particularly useful for string manipulation, such as modifying text, sanitizing inputs, or formatting data.
Syntax:
searchValue
: This can be either a string or a regular expression. It specifies the substring or pattern to search for in the original string.newValue
: This is the string that will replace the matched substring(s). It can also be a function that returns the replacement string.
Return Value:
- Returns a new string with some or all matches of
searchValue
replaced bynewValue
. The original string remains unchanged.
Example 1: Basic String Replacement
In this example, the substring "World"
is replaced with "JavaScript"
.
Example 2: Case Sensitivity
The replace()
method is case-sensitive, meaning it will only replace substrings that match the exact case.
Example 3: Using Regular Expressions
You can use regular expressions with replace()
for more complex search patterns.
In this example, the regular expression /ain/g
is used to replace all occurrences of "ain"
with "ane"
. The g
flag indicates a global search, meaning all matches will be replaced.
Example 4: Using a Function for Replacement
You can also pass a function as the newValue
argument. This function will be called for each match, allowing for dynamic replacements based on the match.
In this example, the function doubles each price found in the string.
Example 5: Replacing All Occurrences
To replace all occurrences of a substring, you can either use a regular expression with the g
flag or convert the substring to a regular expression.
Example 6: Using Special Replacement Patterns
The newValue
string can also contain special replacement patterns like $&
, $1
, $2
, etc., which represent the matched substring and capture groups, respectively.
In this example, the first and last names are swapped using capture groups.
Summary:
- The
replace()
method in JavaScript is used to search for and replace substrings in a string. - It can take a string or a regular expression as the search value and a string or function as the new value.
- The method returns a new string, leaving the original string unchanged.
- It is case-sensitive and can handle both single and multiple occurrences based on whether a regular expression is used.
- It supports dynamic replacements through a callback function and allows the use of special replacement patterns.