如何替换除第一个匹配项外的所有匹配字符 [英] How to replace all matching characters except the first occurrence
问题描述
我正在尝试使用正则表达式比较JavaScript中的字符串.我想用空字符''替换所有'.'s
和'%'s
,但是要注意的是我不想替换第一次出现的'.'
.
value.replace(/\%\./g, '');
预期结果如下:
.4.5.6.7. ==> .4567
4.5667.444... ==> 4.56667444
..3445.4 ==> .34454
您可以将函数传递给replace
,并跳过第一个匹配项,如下所示:
var i = 0;
value.replace(/[\.\%]/g, function(match) {
return match === "." ? (i++ === 0 ? '.' : '') : '';
});
这是一个没有外部变量的独立版本:
value.replace(/[\.\%]/g, function(match, offset, all) {
return match === "." ? (all.indexOf(".") === offset ? '.' : '') : '';
})
第二个版本使用传递到replace()
函数中的offset
与原始字符串(all
)中找到的第一个.
的索引进行比较.如果它们相同,则正则表达式将其保留为.
.后续匹配的偏移量将比第一个匹配的.
偏移量高,并且将替换为''
. %
将始终替换为''
.
两个版本均导致:
4.5667.444 ... ==> 4.56667444
%4.5667.444 ... ==> 4.5667444
两个版本的演示: http://jsbin.com/xuzoyud/5/ >
I am trying to use regex to compare a string in JavaScript. I want to replace all '.'s
and '%'s
with empty character '' but the catch is I don't want to replace the first occurrence of '.'
.
value.replace(/\%\./g, '');
Expected result like below:
.4.5.6.7. ==> .4567
4.5667.444... ==> 4.56667444
..3445.4 ==> .34454
You can pass in a function to replace
, and skip the first match like this:
var i = 0;
value.replace(/[\.\%]/g, function(match) {
return match === "." ? (i++ === 0 ? '.' : '') : '';
});
Here is a self-contained version with no external variables:
value.replace(/[\.\%]/g, function(match, offset, all) {
return match === "." ? (all.indexOf(".") === offset ? '.' : '') : '';
})
This second version uses the offset
passed into the replace()
function to compare against the index of the first .
found in the original string (all
). If they are the same, the regex leaves it as a .
. Subsequent matches will have a higher offset than the first .
matched, and will be replaced with a ''
. %
will always be replaced with a ''
.
Both versions result in:
4.5667.444... ==> 4.56667444
%4.5667.444... ==> 4.5667444
Demo of both versions: http://jsbin.com/xuzoyud/5/
这篇关于如何替换除第一个匹配项外的所有匹配字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!