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

© . All rights reserved.