当前位置:网站首页>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']
边栏推荐
- Usage of JOIN in MySQL
- Advanced gradient of skeleton effect, suitable for waiting for pictures
- [Mianjing] Mihayou data development on one side and two sides
- 骨架效果 之高级渐变,适用图片等待时
- nucleo stm32 h743 FREERTOS CUBE MX配置小记录
- C语言的变长数组
- 3 minutes to take you to understand WeChat applet development
- js takes the value of a feature at a certain position in the string, such as Huawei=> Huawei
- Chapter 10 Clustering
- Questions about your resume
猜你喜欢

最新,每天填坑,Jeston TX1 精卫填坑,第一步:刷机

环形链表---------约瑟夫问题

STM32 map文件解析

Advanced gradient of skeleton effect, suitable for waiting for pictures

npm --package.json---require

DSPE-PEG-DBCO Phospholipid-Polyethylene Glycol-Dibenzocyclooctyne A Linear Heterobifunctional Pegylation Reagent

parser = argparse.ArgumentParser() parsing

URL module

解决glob()返回文件排序不一致问题&onnx本地按照安装方法

6.27面试集
随机推荐
URL模块
第一篇博客
js 取字符串中某位置某特征的值,如华为(Huawei)=>华为
__dirname
Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
ThunderBirde无法登录问题、pycharm调试一直收集数据、RuntimeError: CUDA error: device-side assert triggered等疑难杂症解决
相对路径和绝对路径
querystring模块
Relative and absolute paths
猴子选大王
npm--package.json---require
Small program van-cell line wrapping can be left-aligned
微信小程序云开发-证件照的实现
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine supply, MW: 5000
js scope and closure
微信小程序怎么批量生成带参数的小程序码?
C语言 void和void *(无类型指针)
FreeRTOS内核详解(1) —— 临界段保护原理
DOM manipulation---magnifying glass case
钟表刻度线