Use Regex to form a number without leading zeros in Javascript

I'm having trouble generating a regular expression that can infer leading zeros from numbers represented as strings. Sorry, parseFloat is not what I am looking for since I will deal with 30 + decimal numbers.

Current current regular expression

/(?!-)?(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 failing?

+5
source share
3 answers

It completes all your affairs

var re = /^(-)?0+(?=\d)/;
return val.toString().replace( re, '$1');

^ matches the beginning of a line.

(-)?matches optional -, this will be inserted into the replacement string.

(0+)(?=\d) 0 . (?=\d) lookahead assertion, , , .

+4

:

var r = function(val){
    var re = /^(-?)(0+)(0\.|[1-9])/;
    return val.toString().replace( re, '$1$3');
};
+2

You can use the following:

var r = function(val) {
    var re = /(-)?0*(\d.*)/;
    var matches = val.toString().match(re);
    return (matches[1] || '') + matches[2];
};
+1
source

All Articles