Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading