Commas messing with number input in Javascript

MrGlass picture MrGlass · Feb 14, 2012 · Viewed 27.8k times · Source

I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.

How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.

Answer

adelphus picture adelphus · Feb 14, 2012

Use a global regular expression to replace all commas with an empty string:

var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);