Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

javascript - How to replace all matching characters except the first occurrence

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...