我们来详细解释 JavaScript 中 String.prototype.replace() 方法。
replace() 方法详解
replace() 方法用于在字符串中查找指定的内容(可以是子字符串或正则表达式),并将其替换为新的内容,然后返回一个新的字符串。原字符串不会被修改。
语法
str.replace(regexp|substr, newSubstr|function)
-
str: 调用replace方法的源字符串。 -
regexp | substr: 指定要查找的内容。regexp(正则表达式): 一个正则表达式对象,或者一个包含正则表达式的字符串。如果regexp具有全局标志g,则会替换所有匹配项;否则,只替换第一个匹配项。substr(字符串): 要被替换的字符串。只会替换第一个匹配的子串。
-
newSubstr | function: 指定要替换为的内容。newSubstr(字符串): 新的字符串,用来替换查找到的内容。function(替换函数): 一个函数,它的返回值将被用来替换匹配项。
1. 使用字符串 substr 作为查找目标
当第一个参数是字符串时,replace 只会替换第一次出现的匹配项。
let str = "hello world hello universe";
let newStr = str.replace("hello", "hi");
console.log(newStr); // 输出: "hi world hello universe"
console.log(str); // 输出: "hello world hello universe" (原字符串不变)
2. 使用正则表达式 regexp 作为查找目标
这是更强大和常用的方式,因为它提供了模式匹配的能力。
- 不带
g标志: 只替换第一个匹配项。 - 带
g标志 (global) : 替换所有匹配项。
示例 1: 不带 g 标志
let str = "hello world hello universe";
let newStr = str.replace(/hello/, "hi"); // 正则表达式 /hello/
console.log(newStr); // 输出: "hi world hello universe"
示例 2: 带 g 标志
let str = "hello world hello universe";
let newStr = str.replace(/hello/g, "hi"); // /hello/g 匹配所有 "hello"
console.log(newStr); // 输出: "hi world hi universe"
3. 使用字符串作为 newSubstr (替换内容)
这是最常见的替换方式,直接用一个固定的字符串替换匹配的部分。
let str = "The quick brown fox jumps over the lazy dog.";
let newStr = str.replace(/brown/g, "red");
console.log(newStr); // 输出: "The quick red fox jumps over the lazy dog."
在 newSubstr 中使用特殊模式:
在替换字符串中,可以使用一些特殊的 $ 符号序列来插入匹配信息:
$$: 插入一个美元符号$。$&: 插入匹配到的子串。- $ ``: 插入匹配子串之前的文本。
$ ': 插入匹配子串之后的文本。$ n: 插入第 n 个捕获组的内容(n 是两位数字,如$01,$02...$99)。$ Nn: 插入第 N 个捕获组的内容(N 是一位数字,n 是一位数字,用于区分 Nn)。
示例: 使用 $ &
let str = "abc def ghi";
let newStr = str.replace(/def/g, "($&)"); // $& 代表匹配到的 "def"
console.log(newStr); // 输出: "abc (def) ghi"
4. 使用函数作为 function (替换函数)
当需要动态生成替换内容时,使用替换函数非常有用。函数会被调用,每次匹配时都会执行,并接收特定的参数。
语法:
function replacementFunction(match, p1, p2, ..., pN, offset, string) {
// match: 匹配到的子串
// p1, p2, ..., pN: 匹配到的捕获组 (如果正则表达式中有括号)
// offset: 匹配到的子串在原字符串中的索引位置
// string: 原始字符串
// 返回值: 用于替换的字符串
}
示例: 将数字翻倍
let str = "There are 3 cats and 5 dogs.";
let newStr = str.replace(/\d+/g, function(match) {
// match 是匹配到的数字字符串 ("3", "5")
return parseInt(match) * 2; // 转换为数字,翻倍,再转回字符串
});
console.log(newStr); // 输出: "There are 6 cats and 10 dogs."
示例: 使用捕获组
let str = "John Smith, Jane Doe";
// 正则表达式 (\w+) (\w+) 捕获姓和名
let newStr = str.replace(/(\w+) (\w+)/g, function(match, firstName, lastName) {
// match: "John Smith", "Jane Doe"
// firstName: "John", "Jane"
// lastName: "Smith", "Doe"
return lastName + ", " + firstName; // 交换顺序
});
console.log(newStr); // 输出: "Smith, John, Doe, Jane"