Commas messing with number input in Javascript

爱⌒轻易说出口 提交于 2019-11-26 11:24:55

问题


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.


回答1:


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);



回答2:


or even better

var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));



回答3:


Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:

var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);




回答4:


maybe

 parseint(ny9000withCommas.replace(/\,/g,""))

lets talk about the restriction :

you can/should allow the user to enter both 9000 & 9,000

you can check validy via REGEX.

in the server side - you should eleminate the commas and treat it as integer.



来源:https://stackoverflow.com/questions/9277948/commas-messing-with-number-input-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!