Quick Tip: Testing if a String Matches a Regex in JavaScript

Share this article

Quick Tip: Testing if a String Matches a Regex in JavaScript

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:

FAQs on Utilizing JavaScript’s match() Method for Advanced String Matching and Regular Expressions

What is the purpose of the match() method in JavaScript?

The match() method in JavaScript is a powerful tool used to retrieve the matches when matching a string against a regular expression. It returns an array of results, including the entire matched string and any parentheses-captured substring matches. If no matches are found, it returns null. This method is particularly useful when you need to manipulate strings or check the presence of specific patterns within a string.

How does the match() method differ from other string methods in JavaScript?

Unlike other string methods such as indexOf() or includes(), the match() method allows for more complex pattern matching. It uses regular expressions, which provide a flexible and concise means to match strings of text. This makes it a more powerful tool for tasks such as form validation, data extraction, and string manipulation.

Can you provide an example of how to use the match() method?

Sure, let’s say you have a string and you want to find all occurrences of the word “test”. Here’s how you can do it:
let str = "This is a test. Test is important.";
let result = str.match(/test/gi);
console.log(result); // ["test", "Test"]
In this example, the regular expression /test/gi is used. The “g” flag means global search, and the “i” flag means case-insensitive search.

What are regular expressions in JavaScript?

Regular expressions, also known as regex or regexp, are patterns used to match character combinations in strings. In JavaScript, regular expressions are objects, which can be defined in two ways: using a literal or using the RegExp constructor. They provide a powerful way to perform pattern matching on certain characters, words, and patterns of characters.

How can I use regular expressions with the match() method?

You can use regular expressions directly as the argument for the match() method. For example, if you want to find all the digits in a string, you can use the \d special character to represent digits in a regular expression:
let str = "The year is 2022.";
let result = str.match(/\d+/g);
console.log(result); // ["2022"]
In this example, \d+ matches one or more digits, and the “g” flag performs a global search for all matches, not just the first one.

What happens if no matches are found when using the match() method?

If no matches are found when using the match() method, it returns null. This can be useful for conditional checks. For example, you can check if the result is null before proceeding with further actions in your code.

Can I use the match() method to replace parts of a string?

While the match() method is primarily used for searching, if you want to replace parts of a string based on a pattern, JavaScript provides the replace() method, which can be used with regular expressions. However, you can use the match() method to find parts of the string that need to be replaced.

How can I capture groups with the match() method?

You can capture groups by using parentheses in your regular expression. The match() method will return these groups as separate elements in the resulting array. For example:
let str = "The year is 2022.";
let result = str.match(/(\d+)/g);
console.log(result); // ["2022"]
In this example, (\d+) is a group that matches one or more digits.

Can I use special characters in my regular expressions with the match() method?

Yes, regular expressions support a range of special characters that allow you to create complex search patterns. For example, \d represents any digit, \w represents any alphanumeric character, and . represents any character except for newline characters.

What are the limitations of the match() method?

While the match() method is powerful, it does have some limitations. It can only be used with strings, not with other data types. Also, it can only return an array of results or null, not a boolean value. If you need a boolean result, you may want to use the test() method of the RegExp object instead.

Dianne PenaDianne Pena
View Author

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

JS Quick Tipsregexregular expressions
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week