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


i trying use regex compare string in javascript. want replace '.'s , '%'s empty character '' catch don't want replace first occurrence of '.'.

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

expected result below:

.4.5.6.7. ==> .4567 4.5667.444... ==> 4.56667444 ..3445.4 ==> .34454 

you can pass in function replace, , skip first match this:

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

here self-contained version no external variables:

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

this second version uses offset passed replace() function compare against index of first . found in original string (all). if same, regex leaves .. subsequent matches have higher offset first . matched, , replaced ''. % replaced ''.


both versions result in:

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

demo of both versions: http://jsbin.com/xuzoyud/5/


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -