JavaScript 字符串 replaceAll() 方法
JavaScript 字符串 replaceAll() 方法将值或正则表达式作为模式进行搜索,并返回一个新字符串,其中所有出现的模式都被指定的替换项替换。
模式可以是字符串或正则表达式,替换项可以是字符串或函数。该方法不会更改原始字符串,而是返回一个新字符串。
以下是 replace() 和 replaceAll() 方法之间的区别 -
replace() 方法仅将搜索值或正则表达式的第一次出现替换为指定的替换值,例如:",tutorials,point,".replace(",", "") 返回 "tutorials,point,",而 replaceAll() 方法将搜索值或正则表达式的所有出现替换为指定的替换值。
语法
以下是 JavaScript 字符串 replaceAll() 方法的语法 -
replaceAll(pattern, replacement)
参数
此方法接受两个参数,例如: 'pattern' 和 'replacement',如下所述 -
- pattern - 字符串或正则表达式被替换项替换。
- replacement - 字符串或函数替换了模式。
返回值
String.replaceAll(pattern, replacement) 方法返回一个新字符串,其中所有与模式匹配的内容都被替换项替换。
示例 1
在此程序中,我们使用 JavaScript 字符串 replaceAll() 方法将字符串"Tutorials Point"中的字符串"Point"替换为"point"。
<html>
<head>
<title>JavaScript String replaceAll() Method</title>
</head>
<body>
<script>
const str = "Tutorials Point";
document.write("Original string: ", str);
document.write("<br>New string after replace: ", str.replaceAll("Point", "point"));
</script>
</body>
</html>
输出
上述程序在替换后返回"Tutorials point" -
Original string: Tutorials Point New string after replace: Tutorials point
示例 2
以下是 JavaScript 字符串 replaceAll() 方法的另一个示例。在本例中,我们使用此方法将字符串"Hello World"中的所有空格("")替换为空字符串("")。
<html>
<head>
<title>JavaScript String replaceAll() Method</title>
</head>
<body>
<script>
const str = " Hello World ";
document.write("Original string: ", str);
document.write("<br>New string after replace: ", str.replaceAll(" ", ""));
</script>
</body>
</html>
输出
执行上述程序后,返回替换后的新字符串"HelloWorld"。
Original string: Hello World New string after replace: HelloWorld
示例 3
如果模式为空字符串,则替换将插入到每个 UTF-16 代码单元之间(或每个单词的字符之间)。例如,字符串"Hello"包含五个 UTF-16 代码单元:H、e、l、l 和 o。如果对此字符串使用 replaceAll("", "_"),则将得到"_H_e_l_l_o_"。
<html>
<head>
<title>JavaScript String replaceAll() Method</title>
</head>
<body>
<script>
const str = "TutorialsPoint";
document.write("Original string: ", str);
document.write("<br>String after replcement: ", str.replaceAll("", "_"));
</script>
</body>
</html>
输出
上述程序执行后,返回"_T_u_t_o_r_i_a_l_s_P_o_i_n_t_"。
Original string: Hello String after replcement: _T_u_t_o_r_i_a_l_s_P_o_i_n_t_
示例 4
当正则表达式对象未设置全局标志时,它会抛出"TypeError"异常。
<html>
<head>
<title>JavaScript String replaceAll() Method</title>
</head>
<body>
<script>
const str = "abbabba"
document.write("Original string: ", str);
try {
document.write("<br>String after replacement: ", str.replaceAll(/b/, "-"));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
上述程序抛出了"TypeError"异常。
Original string: abbabba TypeError: String.prototype.replaceAll called with a non-global RegExp argument

