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 Svelte
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Getting Started with Moon.js