Replacing All Occurrences of a Substring
String replaceAll: String.replaceAll()
The replaceAll()
method in JavaScript is used to replace all occurrences of a specified substring with another substring. It returns a new string with all matches of the substring replaced.
Syntax:
The parameters
- searchValue: The substring or regular expression to search for within the string.
- newValue: The string to replace each match of searchValue with.
Return Value:
The replaceAll()
method returns a new string where all occurrences of the searchValue
have been replaced by the newValue
.
Example
In this example, the replaceAll()
method is used to replace all occurrences of the substring ‘Hello’ with ‘Hi’. The result, "Hi, world! Hi again, world!"
, is stored in the variable replacedHello
.
In this example, the replaceAll()
method is used to attempt to replace the substring ‘universe’, which is not present in the string ‘Hello, world!‘. Since ‘universe’ is not found, the original string is returned unchanged.
In this example, a regular expression /world/g
is used with the replaceAll()
method to replace all occurrences of ‘world’ with ‘earth’. The result is "Hello, earth! Hello again, earth!"
.
In this example, the replaceAll()
method attempts to replace the lowercase ‘hello’ in the string ‘Hello, world!‘. Since the method is case-sensitive, no replacement occurs, and the original string is returned.
In this example, the replaceAll()
method is used to replace the special character $
with #
in the string. All occurrences of $
are replaced.
In this example, the replaceAll()
method is used to remove all occurrences of ‘world’ by replacing them with an empty string ''
. The result is "Hello, ! Hello again, !"
.