How to replace all matching characters except the first occurrence

ⅰ亾dé卋堺 提交于 2019-12-17 21:28:15

问题


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

回答1:


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/



来源:https://stackoverflow.com/questions/30227218/how-to-replace-all-matching-characters-except-the-first-occurrence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!