逗号搞乱Javascript中的数字输入 [英] Commas messing with number input in Javascript

查看:88
本文介绍了逗号搞乱Javascript中的数字输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中包含一些由用户控制的元素。其中一个是文本输入字段,用户应该输入一个数字。如果用户只输入数字(EG 9000),但是用户使用逗号表示法(9,000),则一切正常.javascript不会将输入视为整数。

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.

如何删除逗号和/或强制输入整数?我尝试使用parseint(),但它似乎不能用逗号。

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.

推荐答案

使用全局正则表达式替换带有空字符串的所有逗号:

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

这篇关于逗号搞乱Javascript中的数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆