变量包含非数字字符时发出警报?

时间:2012-04-24 05:47:17

标签: javascript regex

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

如果它包含任何其他角色,我该如何显示警告?

2 个答案:

答案 0 :(得分:15)

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

Live DEMO

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

答案 1 :(得分:3)

考虑:

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

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