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
廣告