一、replace
replace方法可以根据传入的第一个参数对原字符串进行匹配,然后使用第二个参数对匹配到的字符进行替换,返回一个新字符串。
语法:str.replace( str | reg ,str | func )
第一个参数可以是字符串或正则,第二个参数可以是字符串或函数
返回值:一个部分替换或者全部替换的新字符串。根据参数的类型不同,返回的结果也会有变化
//第一个参数是字符串,第二个参数也是字符串。
//这个时候仅仅会用第二个参数字符串把第一个匹配到的字符串给替换。
const str = 'to be or not to be.'
str.replace('be', 'BE') // to BE or not to be.
//第一个参数是字符串,第二个参数是函数
const str = 'to be or not to be.'
const result = str.replace('be', function(match, index, str) {
// 函数只会被调用一次
// match:'o' 匹配的第一个字符串
// index:1 匹配的字符串在原字符串开始位置到的索引
// str:'to be or not to be.' 原字符串
return match.toUpperCase()
})
result // to BE or not to be.
//第一个参数是正则, 第二个参数是字符串。这时候字符串可以写一些特殊的变量名
const str = 'to be or not to be.'
// 1:不带特殊变量名的字符串
str.replace(/be/, '**') // 'to ** or not to be.' 正则不带g标志,只替换第一个匹配上的字符串
str.replace(/be/g, '**') // 'to ** or not to **.' 带g标志,替换所有匹配的字符串
// 2:带特殊变量名的字符串,特殊变量名包括如下:
//$$:插入一个'$'
//$&:插入匹配的字符串
//$` 插入当前匹配的字符串前面的字符
//$' 插入当前匹配的字符串后面的字符
//$n 插入第n个括号匹配的字符串。如果不存在第n个分组,那么将会把匹配的字符串替换为$n的字面量内容。
//比如不存在第三个分组,那么将会把'$3'替换为匹配的字符串
//$<name> 这里name代表分组的名称。如果正则表达式中不存在分组或者没有匹配,这个变量将被处理为空字符串
str.replace(/be/g, '$$') // 'to $ or not to $.'
str.replace(/be/g, '($&)') // 'to (be) or not to (be).'
str.replace(/be/g, '($`)') // 'to (to ) or not to (to be or not to ).'
str.replace(/be/g, "($')") // 'to ( or not to be.) or not to (.).'
str.replace(/(to)\s(be)/g, '$1') // 'to or not to.'
str.replace(/(to)\s(be)/g, '$3') // '$3 or not $3.'
str.replace(/(?<T>to)\s(?<B>be)/g, '$<T>$<B>') // 'tobe or not tobe.' ?<T>是对分组命名的写法,T就是这个分组的名称
//第一个参数是正则,第二个参数是函数
const str = 'to be or not to be.'
const result = str.replace(/(to)\s(be)/g, function(match, g1, g2, index, str) {
// 这里正则如果不带g(全局)标识符,就会只调用一次函数
console.log('match:'+match+', g1:'+g1+', g2:'+g2+', index:'+index+', string:'+string);
//match:to be, g1:to, g2:be, index:0, string:to be or not to be.
//match:to be, g1:to, g2:be, index:13, string:to be or not to be.
//match:匹配到的字符串,index:匹配到的字符串在原字符串中的开始位置的索引,string:原字符串
//g1和g2表示的是正则里面的分组个数,有几个分组这里就要写几个参数。如果少了,后面的参数就会补上
return g1 + '-' + g2
})
console.log(result) // 'to-be or not to-be.'
二、replaceAll
replaceAll方法可以根据传入的第一个参数对原字符串进行匹配,然后使用第二个参数对匹配到的字符进行替换,返回一个新字符串。
语法:str.replaceAll( str|reg , str|func )
第一个参数可以是字符串或正则,第二个参数可以是字符串或函数
返回值:一个被全部替换的新字符串,不会改变原字符串。
// 第一个参数是字符串,第二个参数也是字符串。
//和replace不一样的是,replaceAll会替换掉所有匹配到的字符串
const str = 'to be or not to be.'
str.replaceAll('be', '**') // 'to ** or not to **.'
//第一个参数是字符串,第二个参数是函数。
//和replace不一样的是,replaceAll每匹配一次就会调用一次函数。
const str = 'to be or not to be.'
const result = str.replaceAll('be', function(match, index, string) {
return match.toUpperCase()
})
console.log(result) // 'to BE or not to BE.'
//第一个参数是正则,第二个参数无论是字符串还是函数。
//这个时候正则必须要带上g(全局)标识符否则会报错,其余使用方式和replace方法一样。