Javascript 中的逗号弄乱了数字输入

发布于 2025-01-05 15:35:45 字数 177 浏览 2 评论 0原文

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冰火雁神 2025-01-12 15:35:45

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

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

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);
自由如风 2025-01-12 15:35:45

甚至更好

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

or even better

var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
〃温暖了心ぐ 2025-01-12 15:35:45

或者甚至更好,考虑到用户输入通常不可靠,使用它来删除所有非数字字符:
<代码>

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

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

烟若柳尘 2025-01-12 15:35:45

也许

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

让我们谈谈限制:

您可以/应该允许用户同时输入 9000 和 9000。 9,000

您可以通过 REGEX 检查有效性。

在服务器端 - 您应该删除逗号并将其视为整数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文