String.prototype.replace()
是 JavaScript 中的一个方法,用于在字符串中查找匹配的子串,并将其替换为新的子串。默认情况下,它只会替换第一个匹配项。如果要替换所有匹配项,需要使用正则表达式并设置全局标志 g
。
replace()
更高效。g
标志来替换所有匹配项。let str = "Hello, world!";
let newStr = str.replace("world", "everyone");
console.log(newStr); // 输出: "Hello, everyone!"
let str = "apple, apple pie, apple juice";
let newStr = str.replace(/apple/g, "orange");
console.log(newStr); // 输出: "orange, orange pie, orange juice"
let str = "The price is $10 and $20";
let newStr = str.replace(/\$\d+/g, (match) => {
return parseInt(match.slice(1)) * 2;
});
console.log(newStr); // 输出: "The price is $20 and $40"
replace()
只替换了第一个匹配项?原因:默认情况下,replace()
只会替换第一个匹配项。
解决方法:使用正则表达式并设置全局标志 g
。
let str = "apple, apple pie, apple juice";
let newStr = str.replace(/apple/g, "orange");
解决方法:使用回调函数作为 replace()
的第二个参数。
let str = "The price is $10 and $20";
let newStr = str.replace(/\$\d+/g, (match) => {
return parseInt(match.slice(1)) * 2;
});
通过这些方法,可以灵活地处理各种字符串替换需求。
没有搜到相关的文章