admin管理员组文章数量:1202596
I would like to know what's the best way to check a string for example (mail, password ..Etc).
/^...$/i.exec(a)
vs
/^...$/i.test(a)
- exec returns value
- test true
test:
// 1° way
var mail = req.body.mail;
if(check(mail)){
exec:
// 1° way
var mail = req.body.mail;
if(check(mail)){
// 2° way
var mail = check(req.body.mail);
if(mail){
exec or test ? and what number ( 1° or 2° if exec)
SOLUTION
test is better for this case.
- it will surely be faster.
But the most important
- test performs all his work. While exec did not perform, because more can be done, but we do not need.
- Like said Mattias Buelens, using isMail() it's more logical: is an email: yes or no. While exec: is an email: email or null -> wtf ? lol
I would like to know what's the best way to check a string for example (mail, password ..Etc).
/^...$/i.exec(a)
vs
/^...$/i.test(a)
- exec returns value
- test true
test:
// 1° way
var mail = req.body.mail;
if(check(mail)){
exec:
// 1° way
var mail = req.body.mail;
if(check(mail)){
// 2° way
var mail = check(req.body.mail);
if(mail){
exec or test ? and what number ( 1° or 2° if exec)
SOLUTION
test is better for this case.
- it will surely be faster.
But the most important
- test performs all his work. While exec did not perform, because more can be done, but we do not need.
- Like said Mattias Buelens, using isMail() it's more logical: is an email: yes or no. While exec: is an email: email or null -> wtf ? lol
1 Answer
Reset to default 23If you only need to test an input string to match a regular expression, RegExp.test
is most appropriate. It will give you a boolean
return value which makes it ideal for conditions.
RegExp.exec
gives you an array-like return value with all capture groups and matched indexes. Therefore, it is useful when you need to work with the captured groups or indexes after the match. (Also, it behaves a bit different compared to String.match
when using the global modifier /g
)
Ultimately, it won't matter much in speed or efficiency. The regular expression will still be evaluated and all matching groups and indexes will be available through the global RegExp
object (although it's highly recommended that you use the return values).
As for the if
test, that's just a matter of personal taste. Assigning the result of the regular expression test to a variable with a meaningful name (such as isEmail
) could improve the readability, but other than that they're both fine.
本文标签: JavaScript test vs execStack Overflow
版权声明:本文标题:JavaScript: test vs exec - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738649587a2104794.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.test
will return either a booleantrue
orfalse
so it's optimal for that situation. Both would return values which evaluate totrue
/false
, but if you don't need to store matches or capturing groups then.test
will do. =] – Fabrício Matté Commented Jun 12, 2012 at 21:19