最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

I am trying to use regex to pare 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

I am trying to use regex to pare 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
Share Improve this question edited Sep 14, 2016 at 3:20 user663031 asked May 14, 2015 at 0:07 Rahul DessRahul Dess 2,5972 gold badges22 silver badges43 bronze badges 5
  • 3 Replace the first . with something unique of your choice, then replace it back later? – Tuan Anh Hoang-Vu Commented May 14, 2015 at 0:10
  • hmm i would prefer a robust solution rather than like a hack for now. If there is not other way. I would definetley adapt your suggestion. Thank you @tuananh – Rahul Dess Commented May 14, 2015 at 0:12
  • 1 possible duplicate of Javascript replace, ignore the first match – Tuan Anh Hoang-Vu Commented May 14, 2015 at 0:14
  • @RahulDess I came back and added a self-contained version with no external variables. Please see my additional answer. – Drakes Commented May 15, 2015 at 0:17
  • Thanks @Drakes ..seen your update. – Rahul Dess Commented May 15, 2015 at 4:32
Add a ment  | 

1 Answer 1

Reset to default 9

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 pare 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./xuzoyud/5/

发布评论

评论列表(0)

  1. 暂无评论