javascript中的replace方法

1.replace

调用方法str.replace(regexp|substr, newSubStr|function)

  • regexp,正则表达式

  • substr,需要被替换的字符串

  • newSubStr,用于替换的字符串

  • function,一个用于创建新字符串的函数

1.1 当第一个参数为字符串的时候,只替换第一个匹配的项
var text = 'cat,bat,sat,fat'
var result = text.replace('at','ut') // cut,bat,sat,fat
1.2 替换字符串可以插入下面的特殊变量名
  • $$ 插入一个$

  • $& 插入匹配的子串

  • $` 插入当前匹配的子串左边的内容

  • $' 插入当前匹配的子串右边的内容

  • $n 假设第一个参数是RegExp对象,并且n是个小于100的非负整数,那么插入的是第n个括号匹配的字符串

var text = 'cat,bat,sat,fat'
text.replace('at','$`') // cc,bat,sat,fat
text.replace('at','$\'') // c,bat,sat,fat,bat,sat,fat
text.replace(/(a)(t)/,'$1') // ca,bat,sat,fat
text.replace(/(a)(t)/,'$2') // ct,bat,sat,fat
1.3 第二个参数为函数

如果第二个参数为函数,如果匹配成功,函数就会执行,函数的返回值作为替换字符串。$特殊变量名将不能使用。如果第一参数是正则表达式,并且是全局模式,那么这个方法会被调用多次,每次匹配都会被调用

函数参数如下:

  • match 匹配的字符串,对应$&

  • p1,p2……,如果第一个参数是RegExp对象,则代表第n个括号匹配的字符串,对应$1,$2……

  • offset 匹配的字符串在原字符串中的偏移量

  • string 被匹配的原字符串

var text = 'cat,bat,sat,fat'
var result = text.replace(/(a)(t)/g,function(...args){
	console.log(args)
})
console.log('result:', result)

// 输出结果
// ["at", "a", "t", 1, "cat,bat,sat,fat"]
// ["at", "a", "t", 5, "cat,bat,sat,fat"]
// ["at", "a", "t", 9, "cat,bat,sat,fat"]
// ["at", "a", "t", 13, "cat,bat,sat,fat"]
// result: cundefined,bundefined,sundefined,fundefined  因为我没有返回值,所以是undefined

  

 

猜你喜欢

转载自www.cnblogs.com/gg1234/p/9282313.html
今日推荐