序言
以前从来没有发现replace的强大之处,偶然间发现了这个“宝藏API”,写一篇来“纪念”一下
(其实是脑子不好使怕忘了)

循序渐进,先来
普通的字符串
普通字符串就通过简单地匹配进行替换就可以了,我原本以为replace就是这个用处
const str = 'Hello world'
const newStr = str.replace(/Hello/, 'Hi')
console.log(newStr);

$标记
| 变量名 | 代表的值 | 
|---|---|
| $$ | 插入一个 “$”。 | 
| $& | 插入匹配的内容。 | 
| $` | 插入当前匹配的子串左边的内容。 | 
| $’ | 插入当前匹配的子串右边的内容。 | 
| $n | 假如第一个参数是 RegExp对象,并且 n 是个小于100的非负整数,那么插入第 n 个括号匹配的字符串。提示:索引是从1开始 | 
$n:表示从左到右,正则子表达式(组)匹配到的文本
const str = 'import Vue from "vue"'
const newStr = str.replace(/ from ['|"]([^'"]+)['|"]/, ` from "/@modules/${'$1'}"`)
console.log(newStr);

函数
replace的第二个参数可以是函数,这是最“骚”的地方
const str = 'abcde'
const newStr = str.replace(/(a)(b)(c)/, (s1, s2, s3, s4, s5) => {
  console.log(s1);
  console.log(s2);
  console.log(s3);
  console.log(s4);
  console.log(s5);
  return s4+s3+s2
})
console.log(newStr);
解读一下:replace第一个参数是正则式,匹配到了a,b,c,然后第二个函数的参数分别是:
假设一共匹配了n个子串
param 1:匹配到的字符串
param 2:匹配到的第一个子串
param 3:匹配到的第二个子串
······
param n+1:匹配到的第n个子串
param n+2:匹配到的字符串在原字符串的位置
param n+3:原始字符串

 
         
                     
                     
                     
                     
                   
                  

 
                          