I'm having trouble forming a regular expression that can strips out leading zeros from numbers represented as strings. Sorry but parseFloat isn't what I'm looking for since I'll be dealing with numbers with 30+ decimal places.
My current regular expression is
/(?!-)?(0+)/;
Here are my test cases. http://jsfiddle.net/j9mxd/1/
$(function() {
var r = function(val){
var re = /(?!-)?(0+)/;
return val.toString().replace( re, '');
};
test("positive", function() {
equal( r("000.01"), "0.01" );
equal( r("00.1"), "0.1" );
equal( r("010.01"), "10.01" );
equal( r("0010"), "10" );
equal( r("0010.0"), "10.0" );
equal( r("10010.0"), "10010.0" );
});
test("negative", function() {
equal( r("-000.01"), "-0.01" );
equal( r("-00.1"), "-0.1" );
equal( r("-010.01"), "-10.01" );
equal( r("-0010"), "-10" );
equal( r("-0010.0"), "-10.0" );
equal( r("-10010.0"), "-10010.0" );
});
});
Why are my test cases not passing?
You just need quantifier: str = str. replaceAll("^0+", "");
To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
The '?' means match zero or one space. This will match "Kaleidoscope", as well as all the misspellings that are common, the [] meaning match any of the alternatives within the square brackets.
In JavaScript, you can use regular expressions with RegExp() methods: test() and exec() . There are also some string methods that allow you to pass RegEx as its parameter. They are: match() , replace() , search() , and split() . Executes a search for a match in a string and returns an array of information.
This finishes all your cases
var re = /^(-)?0+(?=\d)/;
return val.toString().replace( re, '$1');
^
matches on the start of the string.
(-)?
matches an optional -
this will be reinserted in the replacement string.
(0+)(?=\d)
matches a series of 0 with a digit following. The (?=\d)
is a lookahead assertion, it does not match but ensure that a digit is following the leading zeros.
This passes your tests, and is relatively easy to read:
var r = function(val){
var re = /^(-?)(0+)(0\.|[1-9])/;
return val.toString().replace( re, '$1$3');
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With