String.prototype.replace()
是 JavaScript 中的一个非常常用的字符串方法,用于在字符串中替换匹配到的子串或字符。这个方法基于提供的是字符串还是正则表达式,其工作方式略有不同。
str.replace(regexp|substr, newSubstr|function)
regexp
(正则表达式)或 substr
(要替换的子字符串):必需。要被替换的子字符串或匹配正则表达式的子字符串。newSubstr
(新子字符串)或 function
(回调函数):必需。用于替换的新子字符串或生成新子字符串的回调函数。let str = "Hello, world!";
let newStr = str.replace("world", "JavaScript");
console.log(newStr); // 输出 "Hello, JavaScript!"
let str = "I have 3 apples and 5 oranges.";
let newStr = str.replace(/\d+/g, function(match) {
return parseInt(match) * 2;
});
console.log(newStr); // 输出 "I have 6 apples and 10 oranges."
replace
方法只替换了第一个匹配项?g
,以替换所有匹配项。let str = "foo bar foo baz";
let newStr = str.replace(/foo/g, "qux");
console.log(newStr); // 输出 "qux bar qux baz"
replace
方法进行复杂的替换操作?replace
方法的第二个参数。回调函数可以接收匹配项、捕获组、匹配位置等信息,并返回要替换的新子字符串。let str = "I have 3 apples and 5 oranges.";
let newStr = str.replace(/\d+/g, function(match) {
return "number: " + match;
});
console.log(newStr); // 输出 "I have number: 3 apples and number: 5 oranges."
高校公开课
开箱吧腾讯云
开箱吧腾讯云
开箱吧腾讯云
云+社区沙龙online
企业创新在线学堂
云+社区沙龙online第6期[开源之道]
领取专属 10元无门槛券
手把手带您无忧上云