This method is a called against a regular expression and returns the matching values in the string. The return value is an array containing the matched values. If no matches are found within the string,
null is returned.
""hello world"".match(/[el]/gi) // [""e"", ""l"", ""l"", ""l""]
const matchedStrings = string.match(regex)
This is the regular expression to search for within the string -
It returns an array of all matched characters in the string.
This method can be used to extract info from a string. Like getting an email address from a sentence.
// Create a string const email = 'firstname.lastname@example.org is my email, but i also use email@example.com or firstname.lastname@example.org'; // Create a regex to match all email const re = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi; // Find emails in string const matches = email.match(re); // Display output console.log(matches) // ["email@example.com","firstname.lastname@example.org","email@example.com"]
Want to improve your coding and design skills?
I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.
We value your privacy. 1-click unsubscribe.
Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.
What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)