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?
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 or bool (remember also that JavaScript doesn't allow true function overloading).
See regex.test V.S. string.match to know if a string matches a regular expression
String.match returns 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 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.