admin管理员组文章数量:1321070
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
1 Answer
Reset to default 9You 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/
本文标签: javascriptHow to replace all matching characters except the first occurrenceStack Overflow
版权声明:本文标题:javascript - How to replace all matching characters except the first occurrence - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742091410a2420288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论