The Other Methods

Familiarize yourself with the test method and learn how to override the RegExp class to provide custom behavior.

The exec method is potentially the only method you will care about 90% of the time when dealing with this object. However, there are other methods that might come in handy when trying to do some advanced operations with regular expressions.

The test method

The test method is similar to the previous one, but it only returns true or false depending on whether there are any matches or not. The other methods available from this object are actually internally used by other objects, such as String, to perform the matches.

Overriding the RegExp class

You can, however, override these methods by extending the RegExp class and adding your own logic on top of their behavior. These methods are:

  • match: It is very similar to the exec method. However, it is called internally by the String class method, match.

  • matchAll: This method attempts to improve upon the previous one by returning an iterator instead of a simple list of results, allowing you to use a for…of loop with the returned entity. You can say that this is just syntactic sugar, but it helps keep the code clean.

  • replace: This is the method called by the replace method of the String object.

  • search: Again used by the String class, it returns the index at which the pattern is matched against a given string.

  • split: Used by the String method when its split method is called.

In any case, these methods are not accessible easily to the user. In fact, the only easy way to override them and provide custom behavior for them is to extend the RegExp class, as seen below.

Get hands-on with 1200+ tech skills courses.