0

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?

Tepa6auT
  • 31
  • 3
  • 1
    I'd like to ask you the opposite. Is there any valid reason for not allowing regexp to be used with string or string to be used with regexp? What's the justification for removing one of the two methods? – slebetman Jun 08 '20 at 07:31
  • 1
    "Why do they take /regex/ and 'string' vice versa?" Matching string over regexp requires you to have both. Having one as a context kinda implies you need the other as an argument. How would you suggest those methods to be implemented differently? – Yury Tarabanko Jun 08 '20 at 07:36
  • as i understood that means that it works that way : ```context.method(argument)``` and the context return a response? – Tepa6auT Jun 09 '20 at 08:36

1 Answers1

3

(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.

Dai
  • 141,631
  • 28
  • 261
  • 374