JavaScript Glossary - Lesson #25

JavaScript String .match() Method

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)

regex This is the regular expression to search for within the string - required

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 = ' is my email, but i also use or';

// 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) // ["","",""]

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

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)