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 TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js