Basic Usage(基本用法)
First, let's see what each function does:
(首先,让我们看看每个函数的作用:)
regexObject .
(regexObject 。)
test ( String )(测试 ( 字符串 ))
Executes the search for a match between a regular expression and a specified string.
(执行正则表达式与指定字符串之间匹配的搜索。)
Returns true or false .(返回true或false 。)
string .
(字符串 。)
match ( RegExp )(匹配 ( RegExp ))
Used to retrieve the matches when matching a string against a regular expression.
(用于在将字符串与正则表达式匹配时检索匹配项。)
Returns an array with the matches or null
if there are none.(返回带匹配的数组,如果没有则返回null
。)
Since null
evaluates to false
,
(由于null
计算结果为false
,)
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Performance(性能)
Is there any difference regarding performance?
(表现有什么不同吗?)
Yes .
(是的)
I found this short note in the MDN site :(我在MDN网站上发现了这个简短的说明:)
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
(如果您需要知道字符串是否与正则表达式regexp匹配,请使用regexp.test(string)。)
Is the difference significant?
(差异显着吗?)
The answer once more is YES !
(答案再一次是肯定的 !)
This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:(我把这个jsPerf放在一起显示差异是~30% - ~60%取决于浏览器:)
Conclusion(结论)
Use .test
if you want a faster boolean check.
(如果您想要更快的布尔检查,请使用.test
。)
Use .match
to retrieve all matches when using the g
global flag.(使用.match
在使用g
全局标志时检索所有匹配项。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…