Testing if a String Matches a Regex in JavaScript — SitePoint

In this brief tutorial on JavaScript regex matching, you’ll learn how to test whether a string matches a regular expression using the test() method.

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

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

JavaScript regex matching allows you to check if a string contains a specific pattern, substring, or types of characters. 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 whether 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 if the string matches the regular expression or not.

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

For example:

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 can be separated by zero or more occurrences of any character.

If test() returns true, Matched is logged in the console. Otherwise, Not Matched is logged in the console.

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

You can also use the RegExp constructor to declare the 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 out 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 how to use JavaScript regex matching to test common use cases. It should be noted that the regular expressions here might not be the perfect solution in each case. They’re each used to give a simple example of how the process works.

Testing 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 begin with http:// or https://.

Testing Emails

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

See the Pen
Test is a String is an Email in JS
by SitePoint (@SitePoint)
on CodePen.

Testing Dates

You can test if a string is a date using regular expressions. The following CodePen demo shows how it 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 of the formats “DD-MM-YYYY” or “DD/MM/YYYY”.

Other Methods for JavaScript Regex Matching

There are other methods to test whether a string matches a regular expression. This article doesn’t cover them all, but here’s a brief overview of them:

  • match. This method is available on strings. It accepts a regular expression as a parameter and retrieves the parts of the string that match the regular expression, if there are any.
  • search. This method is available on strings. 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.
  • exec. 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 there are any.

Conclusion

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

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

Related reading:


Source link