上一篇咱们介绍到,()
会捕获正则表达式匹配到的内容,那么有时候咱们不希望捕获他们,可以用非捕获元。
1.?:
"hello---hello666hellomm".replace(/(hello(\d+))/g,"$2")
>> 'hello---666hellomm'
"hello---hello666hellomm".replace(/(?:hello(\d+))/g,"$1")
>> 'hello---666hellomm'
上边第一个例子,用了两个括号,匹配了hello+数字
,$2
代表留下被第二个括号捕获的内容(数字)。第二个例子在第一个括号内加了 ?:
,就消除掉了他的捕获,那么可以直接用$1
来替换数字了。
2.?=
"hello---hello666hellomm".replace(/hello(?=(\d+))/g,"")
'hello---666hellomm'
这个例子匹配了hello+数字
,但是不捕获数字。换句话说就是,他匹配了数字前边的hello
,并替换为空字符串。
3.?<=
"hello---hello666hellomm".replace(/(?<=(\d+))hello/g,"")
'hello---hello666mm'
接着示例2,如果想匹配数字后边的hello
,可以用?<=
,这个时候需要把他放在hello
的前边。
4.?!
"hello---hello666hellomm".replace(/hello(?!(\d+))/g,"")
'---hello666mm'
这个例子,匹配了所有后边不是数字的hello
,并且替换为空字符串。
5.?<!
"hello---hello666hellomm".replace(/(?<!(\d+))hello/g,"")
'---666hellomm'
同上,这里匹配了前边不是数字的hello
,并且替换为空字符串。
上一篇:【js正则表达式】从零开始的正则表达式教学二:replace替换
下一篇:axios多次调用一个接口,取消之前的请求办法。