Tip: Testing if a String Matches a Regular Expression in JavaScript

In this short JavaScript regular expression matching tutorial, you will learn how to test if a string matches a regular expression using the test() method.

Strings are pieces of text that can contain various data, such as URLs, phone numbers, names, numbers, etc. In many cases, you need to check whether or not a string contains a piece of text or certain types of characters.

When testing whether a string contains a specific substring, you might be inclined to use a method like indexOf(). However, for more flexible tests and conditions, using regular expressions is a better option.

JavaScript regular expression matching lets you check whether a string contains a pattern, substring, or specific character types. Regular expressions are useful for detecting information in a string that can be written in different formats, such as dates.

Testing strings against regular expressions

To test if a string matches a regular expression, you must first create a regular expression instance. Then you can use the test() method available on the regular expression to check whether the string matches the regular expression or not.

The test() The method accepts one parameter: the string to test against the pattern. It returns a Boolean value indicating whether or not the string matches the regular expression.

For instance:

const pattern = /test.*regular/;
const str = 'I want to test this string against a regular expression';
if (pattern.test(str)) {
  console.log('Matched');
} else {
  console.log('Not Matched');
}

In this example, you create the pattern test.*regular. This pattern means that a string must contain the words test and regular in that order, and that these words may be separated by zero or more occurrences of any character.

Whether test() returns true, Matched is connected to the console. Other, Not Matched is connected to the console.

Since str contains the words test and regularand test precedes regular in the string, it will match the pattern and test() will return true.

You can also use the RegExp constructor to declare patterns:

const pattern = new RegExp('test.*regular');
const str = 'I want to test this string against a regular expression';
if (pattern.test(str)) {
  console.log('Matched');
} else {
  console.log('Not Matched');
}

You can test this in the following CodePen demo.

See the pen
Testing a string against a regular expression by SitePoint (@SitePoint)
on CodePen.

Common examples

This section shows some examples of using JavaScript regular expression matching to test common use cases. It should be noted that regular expressions here may not be the perfect solution in every case. They are each used to give a simple example of how the process works.

Test URLs

You can test if a string is a URL using regular expressions. You can experiment with this using the following CodePen demo.

See the pen
Test if a string is a URL in JavaScript by SitePoint (@SitePoint)
on CodePen.

Please note that the regular expression pattern used above expects the URL to start with http:// Where https://.

Test emails

You can test if a string is a valid email address using regular expressions. The following CodePen demo shows how.

See the pen
The test is a string is an email in JS by SitePoint (@SitePoint)
on CodePen.

Test dates

You can test if a string is a date using regular expressions. The following CodePen demo shows how this can be done.

See the pen
Test if a string is a date in JavaScript by SitePoint (@SitePoint)
on CodePen.

Please note that the regular expression pattern used above expects the date to be in the format “DD-MM-YYYY” or “DD/MM/YYYY”.

Other JavaScript Regex Matching Methods

There are other methods to test if a string matches a regular expression. This article does not cover them all, but here is a brief overview:

  • match. This method is available on channels. It accepts a regular expression as a parameter and retrieves the parts of the string that match the regular expression, if any.
  • look for. This method is available on channels. It accepts a regular expression as a parameter, searches if the regular expression pattern exists in the string, and retrieves the index of the first occurrence of the pattern in the string if it exists.
  • executive. This method is available on regular expressions. It accepts a string as a parameter, searches for the regular expression pattern in the string, and retrieves the results, if any.

Conclusion

Regular expressions are very useful for testing if a string contains a certain pattern or a substring. With JavaScript regular expression matching, you can check if a string is a URL, date, IP address, or other types and formats.

Compared to using other methods like indexOf()the test() The method available on regular expressions gives you more flexibility when testing whether a string matches a pattern or not.

Related reading:

Comments are closed.