Powered by md-Blog  文 - 篇  访客 -

11、正则表达式在 JavaScript(JS) 中的函数 replace() 替换例子说明


  分类:正则表达式  / 
更新:2018-12-25 16:57:32  /  创建:2018-12-25 16:36:40
不要删除
replace() 替换,没有g,一次,有 g 全局
'a2,b3,c4,d5'.replace(/\d/g, 'x');
输出:"ax,bx,cx,dx"
'a2,b3,c4,d5'.replace(/\d/, 'x');
输出:"ax,b3,c4,d5"
函数替换,4个参数 function(匹配字符串,分组内容,index,原字符串)
'a1b2c3d4e5'.replace(/\d/g, function(match, index, origin){
  console.log(index);
  return parseInt(match) + 1;
});
输出:1
     3
     5
     7
     9
     "a2b3c4d5e6"
//分组
'a1b2c3d4e5'.replace(/(\d)(\w)(\d)/g, function(match, g1, g2, g3, index, origin){
  console.log(match);
  return g1 + g3; //此处是match,删掉匹配的字母
});
输出:"1b2"
     "3d4"
     "a12c34e5"
//过滤字母
'a1b2c3d4e5'.replace(/(\w)(\d)/g, function(match, g1, g2,  index, origin){
  console.log(match);
  return g2; //此处是match,删掉所有字母
});
输出:"a1"
     "b2"
     "c3"
     "d4"
     "e5"
     "12345"
//输出原字符串
'a1b2c3d4e5'.replace(/(\w)(\d)/g, function(match, g1, g2, index, origin){
  console.log(origin);
  return g2; //此处是match,删掉匹配的字母
});
输出:"a1b2c3d4e5"
     "a1b2c3d4e5"
     "a1b2c3d4e5"
     "a1b2c3d4e5"
     "a1b2c3d4e5"
     "12345"
//输出index
'a1b2c3d4e5'.replace(/(\w)(\d)/g, function(match, g1, g2, index, origin){
  console.log(index);
  return g2; //此处是match,删掉匹配的字母
});
输出:0
     2
     4
     6
     8
     "12345"

不要删除

小站不易,感谢支持!