JavaScript replaceAll() method
The replaceAll()
method in JavaScript is used to replace all occurrences of a specified substring or pattern in a string with a new substring. Unlike the replace()
method, which replaces only the first occurrence or requires a global regular expression to replace multiple occurrences, replaceAll()
is specifically designed to replace all matches.
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. If using a regular expression, it must have theg
(global) flag.newValue
: This is the string that will replace the matched substring(s). It cannot be a function, unlikereplace()
.
Return Value:
- Returns a new string with all matches of
searchValue
replaced bynewValue
. The original string remains unchanged.
Example 1: Basic Usage
In this example, all occurrences of "World"
are replaced with "JavaScript"
.
Example 2: Using Regular Expressions
You can also use regular expressions, but they must include the g
flag. If you do not use the g
flag, a TypeError
will be thrown.
In this case, the regular expression /ain/g
replaces all instances of "ain"
with "ane"
.
Example 3: Handling Case Sensitivity
The replaceAll()
method is case-sensitive, similar to replace()
.
Only the lowercase "world"
is replaced, while the uppercase "World"
remains unchanged.
Example 4: Special Characters
When using special characters in the searchValue
, you may need to escape them. This is particularly important for characters that have special meanings in regular expressions.
In this example, all occurrences of the dollar sign ($
) are replaced with the euro sign (€
).
Example 5: Performance
replaceAll()
can be more efficient than using replace()
with a global regular expression for replacing all occurrences, as it simplifies the syntax and avoids potential mistakes related to regex patterns.
Example 6: Chaining with Other String Methods
You can also chain replaceAll()
with other string methods for more complex string manipulations.
Here, "cats"
is replaced with "dogs"
, and the entire string is converted to uppercase.
Summary:
- The
replaceAll()
method replaces all occurrences of a specified substring or pattern in a string with a new substring. - It can take a string or a regular expression (with the
g
flag) as the search value and a string as the new value. - The method returns a new string, leaving the original string unchanged, and is case-sensitive.
- It simplifies the syntax for replacing multiple occurrences compared to using
replace()
with a global regex and can handle special characters. replaceAll()
does not allow thenewValue
to be a function; it must always be a string.