方法解释
两种方法都返回一个新字符串,原始字符串保持不变。并且改方法可以传两个参数。
参数一:pattern
。 pattern 可以是一个 字符串 或一个 正则表达式,
参数二:replacement
。 replacement 可以是一个字符串或一个在每次匹配被调用的函数。
下面以参数一 pattern 传参类型不同来做区分。
1. 当 pattern 是字符串,有区别。
当 pattern 是字符串时,replace
只替换匹配到的第一个位置,replaceAll
会替换每一个匹配到的地方。代码如下:
var value = '123-234-234-234'
var pattern = '-'
console.log('replace: ' + value.replace(pattern, '/'))
console.log('replaceAll: ' + value.replaceAll(pattern, '/'))
// 输出:
// replace: 123/234-234-234
// replaceAll: 123/234/234/234
2. 当 pattern 都是正则表达式时,没有区别。
var value = '123-234-234-234'
var pattern = /-/g
console.log('replace: ' + value.replace(pattern, '/'))
console.log('replaceAll: ' + value.replaceAll(pattern, '/'))
// 输出:
// replace: 123/234/234/234
// replaceAll: 123/234/234/234
除此之外,两个函数的第二个参数都可以传入一个函数,用来自定义替换规则。
var value = '123-234-234-234'
var pattern = '-'
value.replace(pattern, (item, index) => {
// item 替换元素,index 替换元素的下标
console.log(item, index)
return '/'
})
// 输出:
// - 3
// 123/234-234-234