允许使用正则表达式的空字符串

Hor*_*ray 1 javascript regex

我正在尝试使用正则表达式检查文本中是否有数字input。这是代码:

var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
    console.log("number");
} else {
    console.log("bad");
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但如果我添加文本,然后一路退格,我就会变得“糟糕”。当文本中没有任何内容时,如何使其记录“良好” input?我不想允许空格,但我想允许一个空的input.

我试过:

var regex = /\s ^[0-9]+$/;
Run Code Online (Sandbox Code Playgroud)

但无论我在 中插入什么input,我总是得到“坏”。

yok*_*oko 5

这可能适合您测试 Exp(^[a-zA-Z0-9]+$)或空字符串(^$)

var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
    console.log("number");
} else {
    console.log("bad");
}
Run Code Online (Sandbox Code Playgroud)