当前位置:网站首页>js 正则中 replace() 使用
js 正则中 replace() 使用
2022-08-02 03:23:00 【星雨668】
一、replace() 是什么?
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串;
replace方法可以接受两个参数:第一个参数可以使RegExp对象或者一个字符串,第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串,那么只会替换第一个字符串。如果想替换所有的字符串,则必须使用正则表达式。
1.1.当第二个参数是字符串时,字符有特殊的含义:
$1,$2,...,$99 匹配第1~99个分组里捕获的文本
$& 匹配到的子串文本
$` 匹配到的子串的左边文本
$' 匹配到的子串的右边文本
$$ 美元符号
例如,把 “2,3,5”,变成 “5=2+3”:
var result = "2,3,5".replace(/(\d+),(\d+),(\d+)/,"$3=$1+$2");
console.log(result);
// 5=2+3
又例如,把 “2,3,5”,变成 “222,333,555”:
var result = "2,3,5".replace(/(\d+)/g,"$&$&$&");
console.log(result);
// 222,333,555
再例如,把 “2+3=5”,变成 “2+3=2+3=5=5”:
var result = "2+3=5".replace(/=/,"$&$`$&$'$&");
console.log(result);
// 2+3=2+3=5=5
我们对最后这个进行一下说明。要把 "2+3=5",变成 "2+3=2+3=5=5",其实就是想办法把 = 替换成
=2+3=5=,其中,$& 匹配的是 =, $` 匹配的是 2+3,$' 匹配的是 5。因此使用 "$&$`$&$'$&" 便达成了目的。
1.2.当第二个参数是函数时
第二个参数是一个函数。函数拥的参数:第一个参数是匹配到的字符串,倒数第二个参数是匹配的位置,最后一个个参数是原字符串。在函数里面可以对字符串进行操作。使用函数作为第二个参数,可以做一些复杂的替换,比如当匹配多个字符时候,可以对不同的字符做不同的替换。
例如,把 “hello world”,变成 “hebba warbd”:
var str="hello world";
var str1=str.replace(/[ol]/g,function(match,index,input){
console.log(index);
if(match=="o"){
return "a";
}
else {
return "b";
}
});
console.log(str1);//hebba warbd
在例如,引入特殊字符:
"1234 2345 3456".replace(/(\d)\d{2}(\d)/g,function(match,$1,$2,index,input){
console.log([match,$1,$2,index,input]);
})
// ['1234', '1', '4', 0, '1234 2345 3456']
// ['2345', '2', '5', 5, '1234 2345 3456']
// ['3456', '3', '6', 10, '1234 2345 3456']
边栏推荐
- 微信小程序云开发如何将页面生成为pdf?
- The difference between the knowledge question and answer session with the knowledge
- 小程序 van-cell 换行能左对齐问题
- C语言 0长度数组/柔性数组
- docker中配置mysql 5.7
- ssm various configuration templates
- C语言 内联函数
- Chemical reagent Phospholipid-polyethylene glycol-hydroxyl, DSPE-PEG-OH, DSPE-PEG-Hydroxyl, MW: 5000
- 5.20今日学习
- URL模块
猜你喜欢

mysql阶段总结

三月底啦啦

网址URL

简单黑马头条项目

微信小程序云开发-证件照的实现

Chapter 10 Clustering

Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG

Chemical reagent Phospholipid-polyethylene glycol-hydroxyl, DSPE-PEG-OH, DSPE-PEG-Hydroxyl, MW: 5000

Advanced gradient of skeleton effect, suitable for waiting for pictures

kettle 安装与配置
随机推荐
URL模块
5.19今日学习
SOCKS5
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
页面加载流程
最新,每天填坑,Jeston TX1 精卫填坑,第一步:刷机
js basics
__dirname
相对路径和绝对路径
啃瓜记录又一天
display,visibility,opacity
枚举法方法:(leetcode1300)转变数组后最接近目标值的数组和
np.unique() function
第一篇博客
解决MySQL创建子视图并查看的时候,字符集报错问题
C语言 内联函数
npm和package.json
【我的创作纪念日】 3周年
Living to detect the Adaptive Normalized Representation Learning for GeneralizableFace Anti - Spoofing reading notes
微信小程序云开发-证件照的实现