Reputation: 11
I'm using the following to make sure a string is only numbers:
myStr.match(/^[0-9]*$/g);
But I'm looking to refine it by ignoring any zeroes at the beginning unless it's the only digit or just returning 0 if it's all zeroes.
I'd like something like this:
myStr = "0"; //--> match = 0
myStr = "00"; //--> match = 0
myStr = "10"; //--> match = 10
myStr = "05"; //--> match = 5
myStr = "000007"; //--> match = 7
I imagine the second line here makes things more tricky since I'm also checking if there are only zeroes. Perhaps this too much for regex alone. I've found plenty of examples of checking if it starts with zero and skipping it, but I'm having difficulty finding something that grabs the rest of the number and just ignore the zeroes.
EDIT: As far as parseInt() goes, unfortunately, this is an After Effects expression which uses an older version of ECMAScript. Something like parseInt("010") returns 8 (octal).
Upvotes: 0
Views: 95
Reputation: 1074365
Without a lookbehind (coming to JavaScript soon!), you'll need a capture group or other logic in addition to the regex.
Here's the capture group version:
/^0*(\d+)$/
(Many thanks to ctwheels for pointing out my earlier one with 0|[1-9]\d*
could be shortened to just \d+
[since we've consumed any leading zeros except enough to satisfy \d+
with the leading 0*
]!)
Example:
var rex = /^0*(\d+)$/;
function test(myStr, expect) {
var match = myStr.match(rex);
var val = match ? match[1] : null;
console.log(myStr, val, val === expect ? "Good" : "ERROR");
}
test("0", "0");
test("00", "0");
test("10", "10");
test("05", "5");
test("000007", "7");
Upvotes: 3