replaceAll() method is used to replace all substrings matching the specified pattern in a string. Its usage is as follows: The parameter regexp specifies the regular expression to be matched. Parameter replacement specifies the string used to replace the match. This method modifies the original string. Special characters in regular expressions must be escaped. If the regex uses the global flag (g), all matches are replaced. If the replacement parameter is undefined, the matching substring will be deleted.
Usage of replaceAll() method
replaceAll() method is used to replace all matches specified in a string A substring of the pattern.
Syntax:
<code class="js">string.replaceAll(regexp, replacement)</code>
Parameters:
Return value:
The new string after replacement.
Usage:
Use regular expression matching:
<code class="js">let str = "Hello, world!"; let newStr = str.replaceAll(/world/, "JavaScript"); // newStr = "Hello, JavaScript!"</code>
Use string matching:
<code class="js">let str = "JavaScript is fun!"; let newStr = str.replaceAll("JavaScript", "Python"); // newStr = "Python is fun!"</code>
Use function as replacement:
<code class="js">let str = "The quick brown fox jumps over the lazy dog"; let newStr = str.replaceAll(/the/g, (match) => match.toUpperCase()); // newStr = "The QUIck brown fox jumps over the lazy dog"</code>
Note:
g
) is used in the regular expression, all matches will be replaced. replacement
parameter is undefined
, the matching substring will be deleted. Example:
<code class="js">// 替换所有数字为 "X" let str = "1234567890"; let newStr = str.replaceAll(/[0-9]/g, "X"); // newStr = "XXXXXXXXXX" // 替换所有元音为大写 let str = "Hello, world!"; let newStr = str.replaceAll(/[aeiou]/gi, (match) => match.toUpperCase()); // newStr = "H3LL0, w0RLD!"</code>
The above is the detailed content of Usage of replaceall() method in js. For more information, please follow other related articles on the PHP Chinese website!