How to Check if a String Matches a RegEx in JavaScript

Updated onbyAlan Morel
How to Check if a String Matches a RegEx in JavaScript

Regular expressions are a great way to match patterns in text and extract information from the matched text.

When you use them, you sometimes want to know if the string you're using it on matches the pattern you want.

In this post, we'll learn how to check if a string matches a regular expression in JavaScript.

How to check if a string matches a regular expression

JavaScript makes it super simple to test a regular expression against a string.

Let's start with our example string and regex:

const string = "Hello, world!";
const regex = /world/;

To test if the string matches the regex, we can use the test() method.

const string = "Hello, world!";
const regex = /world/;

const results = regex.test(string);

console.log(results);
true

The test() method returns a boolean value indicating whether or not the string matches the regex.

This makes it super simple to use it in our code and decide what to do if the string matches the regex or not.

Another method you can use is the match() method.

const string = "Hello, world!";
const regex = /world/;

const results = string.match(regex);

console.log(results);
0: "world"
groups: undefined
index: 7
input: "Hello, world!"
length: 1

This method will return to you the matches of the regex in the string.

If there is no matches with your regex, it will return null.

In general, if you want to simply know if a string matches a regex, you should use the test() method because it is faster to execute.

However, if you also want to get the matches of the regex, you should use the match() method.

Conclusion

In this post, we learned how to check if a string matches a regular expression in JavaScript.

You can either use the test() method or the match() method, depending on what you want to do.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.