Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Regex to form a number without leading zeros in Javascript

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?

like image 496
Larry Battle Avatar asked May 16 '12 20:05

Larry Battle


People also ask

How do I remove leading zeros in regex?

You just need quantifier: str = str. replaceAll("^0+", "");

How do I express a number in regex?

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.

What is '?' In regex?

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.

Can we use regex in JavaScript?

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.


2 Answers

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.

like image 101
stema Avatar answered Sep 24 '22 13:09

stema


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');
};
like image 29
AD7six Avatar answered Sep 24 '22 13:09

AD7six