How to replace all matching characters except the first occurrence

I am trying to use regex to compare string in JavaScript. I want to replace everything '.'swith '%'san empty character '', but catch I do not want to replace the first occurrence '.'.

value.replace(/\%\./g, '');

Expected Result as shown below:

.4.5.6.7. ==> .4567
4.5667.444... ==> 4.56667444
..3445.4 ==> .34454
+4
source share
1 answer

You can pass a function replaceand skip the first match as follows:

var i = 0;
value.replace(/[\.\%]/g, function(match) { 
    return match === "." ? (i++ === 0 ? '.' : '') : ''; 
});

Here is a standalone version without external variables:

value.replace(/[\.\%]/g, function(match, offset, all) { 
   return match === "." ? (all.indexOf(".") === offset ? '.' : '') : ''; 
}) 

offset, replace() ., (all). , .. , ., ''. % ''.


:

4.5667.444... == > 4.56667444
% 4.5667.444... == > 4.5667444

: http://jsbin.com/xuzoyud/5/

+7

All Articles