当前位置:网站首页>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']
边栏推荐
- UserWarning:火炬。meshgrid:在以后的版本中,它将被要求通过索引ing argu
- Debian 10 NTP Service Configuration
- The difference between the knowledge question and answer session with the knowledge
- DOM操作---放大镜案例
- canvas--pie chart
- C语言 内联函数
- 3 minutes to take you to understand WeChat applet development
- ModuleNotFoundError No module named 'xxx' possible solutions
- 暴力方法求解(leetcode14)查找字符串数组中的最大公共前缀
- Circular linked list---------Joseph problem
猜你喜欢
随机推荐
1.11今日学习
meime module
【装机】老毛桃的安装及使用
js takes the value of a feature at a certain position in the string, such as Huawei=> Huawei
广州华为面试总结
新工程加载YOLOV6的预训练权重问题
Common methods of js array deduplication
骨架效果 之高级渐变,适用图片等待时
Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
三元判断再三元判断
微信小程序自定义swiper轮播图面板指示点|小圆点|进度条
vue3 访问数据库中的数据
DOM manipulation---magnifying glass case
最新,每天填坑,Jeston TX1 精卫填坑,第一步:刷机
debian 10 nat and routing forwarding
环形链表---------约瑟夫问题
Problems when yolov5 calls ip camera
Deveco studio Hongmeng app access network detailed process (js)
C语言 结构体定义方法
display,visibility,opacity









