2

In JavaScript, the syntax to search for a match of regex in string is string.search(regex). Similarly with match, replace, and split.

So why is the regex/string order reversed in the case of test, as in regex.test(string)? Why not string.test(regex) as with the other regex functions?

7
  • 2
    Because test is a method of the RegExp object. So you're testing the regex to match a string. Is not a syntax issue is just a built-in method. You could implement your own String.test method if that's what you want. jsbin.com/bejikabedi/1/edit?js,console Commented Apr 23, 2017 at 4:00
  • Well sure, but that's all clear just from the syntax itself, so that doesn't really explain it. Why is test a method of the RegExp object while match etc. are not? Commented Apr 23, 2017 at 4:09
  • 1
    I guess a simple way to think about it is that, a string cannot test a regular expression, but it makes total sense for a regex to test a string. Commented Apr 23, 2017 at 4:15
  • That makes some sense. But does it also makes sense for a string to match, to replace, and to split a regex, and not the other way around? Sorry, I'm not really seeing it yet. The inconsistency bothers me! Commented Apr 23, 2017 at 4:18
  • 1
    Different people likely worked on the separate methods, hence the inconsistency. Commented Apr 23, 2017 at 4:35

1 Answer 1

2

So why is the regex/string order reversed in the case of test, as in regex.test(string)? Why not string.test(regex) as with the other regex functions?

Because that is the way the language is designed. SO is not the place for discussions or speculation about such language design decisions, the background for which is in many cases lost in the mists of time.

If you're so intent on having a String#test function, then

String.prototype.test = function(re) { return re.test(this); };

or

String.prototype.test = function(re) { return this.search(re) !== -1; };

with all the normal caveats about the dangers of augmenting the prototypes of built-in types.

Sign up to request clarification or add additional context in comments.

1 Comment

Silly me, I thought SO was the place for discussion of such language design decisions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.