I just learned about those methods and tried to google it, but found nothing
'string'.match(/regex/);
/regex/.test('string');
Why do they take /regex/
and 'string'
vice versa?
(Reposting my comment as an answer)
Because a String
isn't a RegExp
and vice-versa.
If the JavaScript standard library did use the same function name in both cases then it would cause confusion because the two methods return very different values.
JavaScript does not implement static-typing so without using the different names match
and test
someone reading the code wouldn't know if the return value type is string[] | null
string[] | null
or bool
(remember also that JavaScript doesn't allow true function overloading).
See regex.test VS string.match to know if a string matches a regular expression
String.match
returns string[] | null
string[] | null
. RegExp.test
returns bool
. So if you see this code...:
function doSomething( foo, bar ) {
return foo.match( bar );
}
...then (assuming foo
is a string
) then you know that doSomething
will return a string[] | null
string[] | null
value.
And if you see this...:
function doSomething( foo, bar ) {
return foo.test( bar );
}
...Then (assuming foo
is a RegExp
) then you know that doSomething
will return a bool
value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.