Reputation: 403
I'm trying to match the leading zeros of a string to replace with an empty string. I can have a scenario with leading zeros such that there is a decimal: 0000000.005
or without: 000000000005
.
I've come up with: /.+?(?=0\.)|.+?(?=[0-9]+)/
.
The first part matches all the leading zeroes up until I reach a 0.
pattern (i.e. 0000000.005
becomes 0.005
). The second part applies the same lazy, positive lookahead approach to leading zeros without a decimal (i.e. 000000000005
becomes 5
).
Since the second part (.+?(?=[0-9]+)
) is stronger than the first, it will always turn 0000000.005
into 5
. Is there a way to, in one expression, only match using the first section if there is, say the presence of a decimal, and to use the other expression if not?
Thanks!
Upvotes: 1
Views: 56
Reputation: 626747
If you need a regex solution, you may use
s.replace(/^0+(?=0\.|[1-9])/, '')
See the regex demo.
Details
^
- start of string0+
- 1+ zeros(?=0\.|[1-9])
- the next chars should be 0.
or a digit from 1
to 9
.JS demo:
var strs = ['000000000005', '0000000.005'];
for (var s of strs) {
console.log(s, '=>', s.replace(/^0+(?=0\.|[1-9])/, ''));
console.log(s, '=>', Number(s)); // Non-regex way
}
Upvotes: 2
Reputation: 7949
You can use the replace()
fucntion in regex.
Here is the demo code .
var str = "00000000.00005";
var str1 = "0000000005";
if(str.includes(".")) //case 1
{
str = str.replace(/0+\./g, '0.');
console.log("str ==>", str);
}
if(!str1.includes("."))//case 2 .
{
str1 = str1.replace(/0+\.|0+/g, '');
console.log("str 1 ===>", str1);
}
Upvotes: 0