Skip to content Skip to sidebar Skip to footer

Javascript Regex To Allow Negative Numbers

I am using this regex to allow floating point numbers str.replace(/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2') I need to allow negative numbers also. Any ideas. This allows 123.45 and i

Solution 1:

Here is a shorter regex that matches negative floats:

/^-?[0-9]\d*(\.\d+)?$/

Explaination and demo of this regex

If you want to match explicitly positive numbers like +123.123 along with the negative ones, use the following regex:

/^[-+]?[0-9]\d*(\.\d+)?$/

Source

Solution 2:

Use this regex:

(?!=\A|\s)(-|)[\d^]*\.[\d]*(?=\s|\z)

It will match all floating point numbers. Demo: https://regex101.com/r/lE3gV5/2

Solution 3:

Try the following,

str.replace(/-?[0-9]+(\.[0-9]+)?/g,'')

                 OR 

str.match(/^-?[0-9]+(?:\.[0-9]+)?$/,'')

Solution 4:

You can try this Regex:

parseFloat(str.replace(/.*?(\-?)(\d*\.\d+)[^\d\.]*/, '$1$2'));

But its better to match the number than replace the other characters:

var matches = /(\-?\d*\.(?:\d+)?)/.exec(str);
if (typeof matches != 'undefined' && matches.length > 0) {
    var num = parseFloat(matches[1]);
}

Solution 5:

You can try to use regexp:

/-?(\d+\.\d+)[^\w\.]/g

DEMO

Post a Comment for "Javascript Regex To Allow Negative Numbers"