查找字符串中是否有字母,如果存在,则返回false

时间:2020-10-26 18:20:06

标签: javascript

为什么这对于查找字符串是否包含字母然后返回false无效? 我该怎么办?

return pin.includes(/[a-z]/) ? false : true

5 个答案:

答案 0 :(得分:0)

因为其中 includes 在其参数中包含一个字符串。 您可以使用 match test

示例:

var regExp = /[a-z]/;
regExp.test('some text'); // return true

示例2:

'some text'.match(/[a-z]/);
'123'.match(/[a-z]/); // return null

答案 1 :(得分:0)

includes()不使用正则表达式。尝试使用match()

let pin = "hello";
console.log(!pin.match(/[a-z]/)); //"!" inverts result to match your logic
pin = "132";
console.log(!pin.match(/[a-z]/));

由于match()的返回值是真实的或虚假的,因此您不需要在示例中使用的三元if / else。

答案 2 :(得分:0)

您需要使用String.prototype.match(regex)函数。

const reg = /[a-zA-Z]/

const func = (s) => !s.match(reg);

console.log(func("465496464[][]"));
console.log(func("4464644aa423164646"));

答案 3 :(得分:0)

您可以使用正则表达式测试方法。测试方法测试字符串中的匹配项,如果找到匹配项,则返回true,否则返回false。

const pin = 'abc123';
const ret = !/[a-zA-Z]/g.test(pin);
console.log(ret);

答案 4 :(得分:0)

尝试一下:

var r = new RegExp(“[a-zA-Z]”);
return r.test(pin);

“ pin”是字符串变量。