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.

js
""hello world"".match(/[el]/gi)
// [""e"", ""l"", ""l"", ""l""]
js
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.

js
// Create a string
const email = 'hello@john.com is my email, but i also use sign@john.com or help@sweets.com';

// 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) // ["hello@john.com","sign@john.com","help@sweets.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

Chris Sev

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

Comments

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