JavaScript 字串 replace() 方法



JavaScript 字串 replace() 方法搜尋某個值或正則表示式,並透過將模式的第一次出現替換為指定的替換內容來返回一個新字串。模式可以是字串或正則表示式,替換內容可以是字串或函式。它不會更改原始字串值,而是返回一個新字串。

如果 pattern 是字串,則只會刪除第一次出現的匹配項。

以下是 replace() 和 replaceAll() 方法之間的區別:

replaceAll() 方法將搜尋值或正則表示式的所有出現都替換為指定的替換內容,例如:"_tutorials_point_".replaceAll("_", "") 返回 "tutorialspoint",而 replace() 方法僅將搜尋值或正則表示式的第一次出現替換為指定的替換內容。

語法

以下是 JavaScript 字串 replace() 方法的語法:

replace(pattern, replacement)

引數

此方法接受兩個引數,例如:“pattern”和“replacement”,如下所述:

  • pattern - 被 replacement 替換的字串或正則表示式。
  • replacement - 用於替換 pattern 的字串或函式。

返回值

此方法返回一個新字串,其中 pattern 的第一次出現被指定的值替換。

示例 1

在此程式中,我們使用 JavaScript 字串 replace() 方法將字串“Point”替換為字串“point”,字串為“Tutorials Point”。

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("Original string: ", str);
   document.write("<br>New string after replacement: ", str.replace("Point", "point"));
</script>
</body>
</html>

輸出

上述程式在替換後返回“Tutorials point”:

Original string: Tutorials Point
New string after replacement: Tutorials point

示例 2

這是 JavaScript 字串 replace() 方法的另一個示例。在此示例中,我們使用 replace() 方法將字串“ Hello World ”中空格(“ ”)的第一次出現替換為空字串(“”)。

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
   const str = " Hello World ";
   document.write("Original string: ", str);
   document.write("<br>New string after replacement: ", str.replace(" ", ""));
</script>
</body>
</html>

輸出

執行上述程式後,它在替換後返回一個新字串“Hello World ”。

Original string: Hello World
New string after replacement: Hello World

示例 3

當搜尋(模式)值為一個空字串時,replace() 方法將替換值插入字串的開頭,在任何其他字元之前。

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
   const str = "TutorialsPoint";
   document.write("Original string: ", str);
   document.write("<br>New string after replace: ", str.replace("", "__"));
</script>
</body>
</html>

輸出

執行上述程式後,它返回“ __TutorialsPoint”。

Original string: TutorialsPoint
New string after replace: __TutorialsPoint

示例 4

在以下程式中,我們將字串“$2”指定為 replace() 方法的替換引數。正則表示式沒有第二組,因此它替換並返回“$2oo”。

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
   const str = "foo";
   let replacement = "$2";
   document.write("Original string: ", str);
   document.write("<br>Replacement: ", replacement);
   document.write("<br>New String after replacement: ", str.replace(/(f)/, replacement));
</script>
</body>
</html>

輸出

上述程式返回“$2oo”。

Original string: foo
Replacement: $2
New String after replacement: $2oo
廣告