美文网首页
string.replace用法详解

string.replace用法详解

作者: 晗笑书生 | 来源:发表于2020-03-15 08:55 被阅读0次

replace的用法

string.replace

* 入参为2个字符串是只替换第一个
* 正则的/g可以全局替换
* 使用正则可以分组
var str = 'abbc'
str.replace('b','a')
// aabc
str.replace(/b/g,'a')
// aaac

str.replace(/(a)(b)(c)/, '$1$2$3')
// 把abc 分三组 $1$2$3 都是标识分组 分别可以代表对应的分组的序号
str.replace(/(a)(b)(c)/, '$3$2$1') // abc -> cba

$` 标识是匹配的左边的内容
'12c34'.replace(/c/, '$`') // 121234 c替换为c左边的12

$' 标识匹配的右边的内容
'12c34'.replace(/c/, "$'") // 123434 c替换为右边的34

$& 标识匹配的内容本身
'12c34'.replace(/c/, "$&") // 12c34
'12c34'.replace(/c/, "$&$&$&")  // 12ccc34 c替换为本身ccc


'abc'.replace(/bc/, function(match){
  console.log(match)
  // 匹配的内容 这里就是bc
})

'abc123'.replace(/\d+/, function(match) {
  console.log(match)
  // 匹配的内容 这里就是123
})

'abc123'.replace(/(a)(b)(c)(\d+)/, function(match, $1,$2,$3,$4){
  console.log(match, $1,$2,$3,$4)
  // abc123 a b c 123
})


'abc123'.replace(/(a)(b)(c)(\d+)/, function(match, $1,$2,$3,$4){
  console.log(match, $1,$2,$3,$4)
  // abc123 a b c 123
  return $4+$1+$2+$3
})
// 123abc
eg:
能实现插入和删除
var str = 'ac'
// ac 变成 abc
str.replace('a', 'ab')
str.replace(/(a)/, '$1b')
str.replace(/a/, "ab")
str.replace(/(a)/, (match, $1) => `${$1}b`)

相关文章

网友评论

      本文标题:string.replace用法详解

      本文链接:https://www.haomeiwen.com/subject/aisxehtx.html