How to use the String match method
Table of Contents
Regular expressions are used to match patterns in strings and use it to extract parts of it out.
When we have a string and regular expression, we can use the match
method to extract the matches of the regular expression.
In this post, we'll look at examples of how to use the match
method in JavaScript.
How to use the match method
As mentioned before, when you have a string and regular expression, the match method can be used to get back the matches.
Let's say you want to get all exact matches:
JAVASCRIPTconst string = "Hello 123456789 World";
const regex = /Hello/;
const matches = string.match(regex);
console.log(matches);
BASH["Hello"]
If you want to match numbers:
JAVASCRIPTconst string = "Hello 123456789 World";
const regex = /\d+/;
const matches = string.match(regex);
console.log(matches);
BASH["123456789"]
If you want to match several exact matches:
JAVASCRIPTconst string = "Hello 123456789 World";
const regex = /(Hello|World)/g;
const matches = string.match(regex);
console.log(matches);
BASH["Hello", "World"]
Hopefully by now you've gotten the point that you can just pass in your regular expression and get back all the valid matches.
Conclusion
In this post, we looked at examples of how to use the match
method in JavaScript.
Simply use the match
method on your desired string and regular expression to get back the valid matches.
Thanks for reading!
- Getting Started with Solid
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API