String.match()

The String.match() method accepts a regular expression as a parameter which is then used to scan a string for any matches.

String.match()

The String.match() method accepts a regular expression as a parameter which is then used to scan a string for any matches.

Syntax 📝

str.match(regex)

Parameters

String.match() requires a regular expression, regex in the above example.

Real World Example 🌎

When you search a word document for a certain word or phrase you're essentially using String.match(). You provide the word processor with a string such as hello and it scans the document for a match. It then returns the number of matches it found and allows you to jump to the part of the page that contains the provided string.


const text = "Hello, World. I love to code every single day. In fact, I love to code every single night, too.";

const regex = /code/g;

text.match(regex); // returns ["code", "code"]

Our regular expression, regex is scanning through text looking for the string code. It finds 2 instances of the string code and as a result, it returns an array which contains both of them, ["code", "code"]. It's important to not the g at the end of regex which is the global flag. The global flag will return all matches of the regular expression. Without the global flag, it would just find the first instance.

Regular Expression

Regular expressions can be a rather lengthy topic, and a little intimidating to newcomers. We won't get into them in this post, but there are a ton of great resources for them. My favorite resource when trying to create a regular expression is regex101.com and the MDN Docs for Regular Expressions.

Wrapping Up ✅

The String.match() method is a powerful and easy to use tool when trying to scan through any kind of text.

Stay Tuned 📺

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]. If you're enjoying my posts, please subscribe below! 👇

Help us improve our content