JavaScript replaceAll() 方法



JavaScript String replaceAll() 方法搜索一个值或正则表达式作为模式,并返回一个新字符串,其中模式的所有出现都被指定的替换项替换。

模式可以是字符串或正则表达式,替换项可以是字符串或函数。此方法不会更改原始字符串,而是返回一个新字符串。

以下是 replace() 和 replaceAll() 方法的区别:

replace() 方法只替换搜索值或正则表达式的第一次出现,例如:",tutorials,point,".replace(",", "") 返回 "tutorials,point,",而 replaceAll() 方法替换搜索值或正则表达式的所有出现。

语法

以下是 JavaScript String replaceAll() 方法的语法:

replaceAll(pattern, replacement)

参数

此方法接受两个参数,例如:'pattern' 和 'replacement',如下所述:

  • pattern - 被 replacement 替换的字符串或正则表达式。
  • replacement - 替换 pattern 的字符串或函数。

返回值

此方法 String.replaceAll(pattern, replacement) 返回一个新字符串,其中 pattern 的所有匹配项都被 replacement 替换。

示例 1

在这个程序中,我们使用 JavaScript String replaceAll() 方法将字符串 "Point" 替换为 "point",字符串为 "Tutorials 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 String 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
广告
© . All rights reserved.