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/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…