How to Check if a String Matches a RegEx in JavaScript
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!
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript