javascript 警告变量是否包含非数字字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10292361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:21:39  来源:igfitidea点击:

Alert if variable contains non numeric characters?

javascriptregex

提问by lisovaccaro

'p' can only store "$", commas, dots or numbers.

'p' 只能存储“$”、逗号、点或数字。

How can I show an alert if it contains any other character?

如果警报包含任何其他字符,如何显示警报?

回答by gdoron is supporting Monica

if (p.match(/[^$,.\d]/))
    alert('error!');

Live DEMO

现场演示

You can use thisExcellentregex cheat sheet.

您可以使用这个优秀的正则表达式备忘单。

回答by RobG

Consider:

考虑:

if (/[^$,\.\d]/.test(p)) {
  // value has characters other than $ , . 0-9.
};

The regular expression testmethod returns a boolean value, whereas matchreturns an array and so is dependent on type conversion when used in a simlar manner.

正则表达式测试方法返回一个布尔值,而match返回一个数组,因此在以类似方式使用时依赖于类型转换。