起因
由于之前自己对replace不熟悉的缘故,写的代码又臭又长,所以特地来深入的了解下replace。
想看具体代码可移步 记一次字符串切割的工作
replace语法
str.replace(regexp|substr, newSubStr|function)
可以看到replace使用正则表达式或字符串来匹配字符串,使用字符串或函数返回值做替换字符串。
如果按不同形式的传参来细分replace的话,我觉得不够好,所以我决定按功能特点进行区分对比。
匹配一个 && 匹配多个
var p = "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
// 匹配一个
console.log(p.replace("the", `123`));
console.log(p.replace(/the/, `123`));
//The quick brown fox jumps over 123 lazy dog. If the dog reacted, was it really lazy?
// 匹配多个
console.log(p.replace(/the/g, `123`));
//The quick brown fox jumps over 123 lazy dog. If 123 dog reacted, was it really lazy?
直接替换 && 根据匹配字符串灵活替换
对比之前先了解MDN文档中对于replace第二个参数的两种形态。
var p = "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
// 直接替换
console.log(p.replace(/the/, `123`));
//The quick brown fox jumps over 123 lazy dog. If the dog reacted, was it really lazy?
// 根据匹配字符串灵活替换
// $& == 替换函数的第一个参数match == 匹配字符串
console.log(p.replace("the", "$&"));
console.log(p.replace("the", match => match));
//The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?
console.log(p.replace(/the/g, "$&123"));
console.log(p.replace(/the/g, match => match+'123'));
//The quick brown fox jumps over the123 lazy dog. If the123 dog reacted, was it really lazy?
// $n == 替换函数的第n+1个参数 == 匹配正则表达式中第n个括号
console.log(p.replace(/(t)(h)(e)/g, "$2"));
console.log(p.replace(/(t)(h)(e)/g, (match,p1,p2,p3) => p2));
//The quick brown fox jumps over h lazy dog. If h dog reacted, was it really lazy?
// 可实际运用于将匹配字符串的第一位转大写的需求
console.log(p.replace(/(t)(h)(e)/g, (match,p1,p2,p3) => p1.toUpperCase()+p2+p3));
//The quick brown fox jumps over The lazy dog. If The dog reacted, was it really lazy?
// $` == 当前匹配的子串左边的内容。 == string.substring(0,offset)
console.log(p.replace("the", "$`"));
console.log(p.replace("the", (match, offset,string) => string.substring(0,offset)));
//The quick brown fox jumps over The quick brown fox jumps over lazy dog. If the dog reacted, was it really lazy?
// $' == 当前匹配的子串右边的内容。 == string.substring(offset+match.length,string.length)
console.log(p.replace("the", "$'"));
console.log(p.replace("the", (match, offset,string) => string.substring(offset+match.length,string.length)));
//The quick brown fox jumps over lazy dog. If the dog reacted, was it really lazy? lazy dog. If the dog reacted, was it really lazy?
注
以上所有引用都为MDN文档中可以找到