Search code examples
javascriptinputnumbers

Javascript Regex Replace Produces <empty string>


I'm kinda at my wits end with this as it is not behaving like other examples I've tried online.

I have some input validation for numbers:

$('body').on("input", 'input[type="number"]', function(){
        const regex = /[^0-9]/g;
        const val = $(this).val();
        console.log(val.replace(regex, ''));

Any time I enter a character that isn't a digit it returns an <empty string> in the console.

I've tried this same code in a few sandboxes and it works perfectly, returning numbers.


Solution

  • When you get the value of a type="number" input, it returns an empty string if the user input is not a valid number. From the HTML spec

    The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.