Table of Contents
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:
JAVASCRIPTconst string = "Hello, world!";
const regex = /world/;
To test if the string matches the regex, we can use the test() method.
JAVASCRIPTconst string = "Hello, world!";
const regex = /world/;
const results = regex.test(string);
console.log(results);
BASHtrue
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.
JAVASCRIPTconst string = "Hello, world!";
const regex = /world/;
const results = string.match(regex);
console.log(results);
BASH0: "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!
How to Install Node on Windows, macOS and Linux
Getting Started with Express
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a MySQL Server using Docker
Getting Started with Sass
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
