在JavaScript中 如何检查字符串是否与 RegEx 匹配

在本教程中,我们建议使用两种方法来检查给定的字符串是否与 RegEx 匹配。

假设我们要检查字符串是否与以下正则表达式匹配:

^([a-z0-9]{5,})$

最简单、最快的方法是正则表达式的 test() 方法。

console.log(/^([a-z0-9]{4,})$/.test('ab1')); //false
console.log(/^([a-z0-9]{4,})$/.test('ab123')); //true
console.log(/^([a-z0-9]{4,})$/.test('ab1234')); //true

match() regex 方法还可用于检查匹配,该匹配检索将字符串与正则表达式匹配的结果:

var str = 'abc123';
if (str.match(/^([a-z0-9]{4,})$/)) {
  console.log("match!");
}

match() 和 test() 方法之间的一个区别是第一个只适用于字符串,后者也适用于整数。

//12345.match(/^([a-z0-9]{5,})$/); //错误,只能字符串使用match
console.log(/^([a-z0-9]{5,})$/.test(12345)); //true
console.log(/^([a-z0-9]{5,})$/.test(null)); //false
console.log(/^([a-z0-9]{5,})$/.test(undefined)); //true

但是,test() 比 match() 快。
使用 test() 进行快速布尔检查。

在使用 g 全局标志时,使用 match() 检索所有匹配项。

Javascript 正则表达式

正则表达式或者正则表达式是用于匹配字符串中字符组合的模式。
正则表达式是 JavaScript 中的对象。

模式与 RegEx exec 和 test 方法以及 String 的 match、replace、search 和 split 方法一起使用。

test() 方法执行搜索正则表达式和指定字符串之间的匹配项。
它返回真或者假。

日期:2020-06-02 22:16:11 来源:oir作者:oir