JavaScript String replace() 方法搜索值或正则表达式,并通过将模式的第一次出现替换为指定的替换来返回新字符串。模式可以是字符串或正则表达式,替换可以是字符串或函数。它不会更改原始字符串值,但会返回一个新字符串。
如果模式是 string,则只会删除第一个匹配项。
以下是 replace() 和 replaceAll() 方法之间的区别 -
replaceAll() 方法将搜索值或正则表达式的所有匹配项替换为指定的替换项,例如:“_qikepu_com_”.replaceAll(“_”, “”) 返回 “qikepucom”,而 replace() 方法仅将搜索值或正则表达式的第一次匹配项替换为指定的替换项。
语法
以下是 JavaScript String replace() 方法的语法 -
replace(pattern, replacement)
参数
此方法接受两个参数,例如:'pattern' 和 'replacement',如下所述 -
- pattern − 替换为 replament 的字符串或正则表达式。
- replacement − 要替换模式的字符串或函数。
返回值
此方法返回一个新字符串,其中第一次出现的模式将替换为指定值。
示例 1
在这个程序中,我们使用 JavaScript String replace() 方法将字符串 “com” 替换为字符串 “qikepu com” 中的 “com”。
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
const str = "Qikepu Com";
document.write("Original string: ", str);
document.write("<br>New string after replacement: ", str.replace("Com", "com"));
</script>
</body>
</html>
输出
上述程序在替换后返回 “Qikepu com” -
New string after replacement: Qikepu com
示例 2
这是 JavaScript String 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>
输出
执行上述程序后,replace 后返回新字符串 “Hello World”。
New string after replacement: Hello World
示例 3
当 search (pattern) 值为空字符串时,replace() 方法会在字符串的开头插入替换值,在任何其他字符之前。
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script>
const str = "QikepuCom";
document.write("Original string: ", str);
document.write("<br>New string after replace: ", str.replace("", "__"));
</script>
</body>
</html>
输出
执行上述程序后,它将返回 “ __QikepuCom”。
New string after replace: __QikepuCom
示例 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”。
Replacement: $2
New String after replacement: $2oo