Search code examples
javascriptjqueryregexnegative-number

Allow numbers in regex including the negative


I have written this regex to remove any thing which is not number.

     var dataTest = data.replace(/[^0-9]/gi, '');

It converts "abc123xyz" to "123"

However now i want to cover negative numbers also :-

      var dataTest = data.replace(/[^-0-9]/gi, ''); 

But it is allowing - in between also. It converts "abc123-xyz" to "123-" I want it to convert to "123"

However, if user gives "-123abc" , it should change to "-123".

I am invoking this code on focusout event in javascript. I will accept solution in jquery also.


Solution

  • One option is to capture the number and remove everything else:

    input = "abc-123def"
    
    clean = input.replace(/.*?(-?\d+).*/, "$1")
    
    document.write(clean)

    or, more efficiently, with match:

     clean = (input.match(/-?\d+/) || [])[0]