replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
它接受两个参数,第一个是匹配旧的字符串,需要字符串或正则表达式;第二个是要替换的新字符串。
语法:string.replace(oldValue,newValue)
使用中需要注意几个容易出错的地方:
① replace()不改变原字符串,而是返回一个新的字符串
let str1 = 'abc'`
let str2 = str.replace("a", "d")
console.log(str1); //输出‘abc’
console.log(str2); //输出'dbc'
② replace()是字符串的方法,如果报错"XXX.replace is not a function",请检查数据类型是否为字符串
let arr = ["a", "b", "c"]; //数组
console.log(arr.replace("a", "d")); // 报错arr.replace is not a function
③ replace()默认情况下仅替换第一个符合条件的字符
let str = 'aabbcc'
console.log(str.replace("a", "d")); //输出'dabbcc'
以下介绍一些使用技巧:
① 如果要匹配所有符合条件字符,可以使用正则+g的方法,需注意在正则中匹配具体的字符不需要加引号:
let str = 'aabbcc'
console.log(str.replace(/a/g, "d")); //输出'ddbbcc'
② 如果匹配的时候要忽略大小写,可以使用正则+i的方法:
let str = 'AaBbCc'
console.log(str.replace(/a/g, "d")); //输出'AdBbCc'
console.log(str.replace(/a/gi, "d")); //输出'ddBbCc'
③ replace()第二个参数可以是回调函数:
let str = "aabbcc";
let total = 0;
console.log(
str.replace(/a/g, () => {
total++;
return "d" + total;
})
); //输出'd1d2bbcc'