JavaScript 字符串 replace() 方法
JavaScript 字符串 replace() 方法搜索一个值或一个正则表达式,并通过用指定的替换值替换模式的第一次出现来返回一个新字符串。模式可以是字符串或正则表达式,替换值可以是字符串或函数。它不会更改原始字符串值,而是返回一个新字符串。
如果 pattern 是字符串,则只会删除第一次出现的字符串。
以下是 replace() 和 replaceAll() 方法之间的区别 -
replaceAll() 方法用指定的替换值替换所有出现的搜索值或正则表达式,例如:"_tutorials_point_".replaceAll("_", "") 返回"tutorialspoint",而 replace() 方法仅用指定的替换值替换第一次出现的搜索值或正则表达式。
语法
以下是 JavaScript 字符串 replace() 方法的语法 -
replace(pattern,replacement)
参数
此方法接受两个参数,例如:'pattern' 和 'replacement',如下所述 -
- pattern - 被替换项替换的字符串或正则表达式。
- replacement - 要替换模式的字符串或函数。
返回值
此方法返回一个新字符串,其中模式的第一次出现被指定值替换。
示例 1
在此程序中,我们使用 JavaScript 字符串 replace() 方法将字符串"Tutorials Point"中的字符串"Point"替换为"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

