DEV Community

loading...

Part 3 : Match and Extract a REGEX with .match() Method

Swarnali Roy
I am a Junior Software Engineer. Learning new things and sharing those with fellow developers.
Updated on ・2 min read

Hello my dear readers!
This is a small part of this series but a very useful one.

Previously, we have known that, .test() method allows us to only check if a pattern exists or not within a string. But we can also extract the actual matches we found , with the .match() method.

Let's get started with that! 👇🏻

Extract Matches from a String using .match() Method

To use the .match() method, we need to apply the method on a string and pass in the regex inside the parentheses.

Before showing the basic syntax of .match() method, let's look at the syntax of .test() method for a moment again.
Basic syntax of .test() method is: regex.test(string)

Now let's look at the basic syntax of .match() method:
string.test(regex)

Did you notice something interesting?! 🧐🤔

Notice that, the .match() syntax is the exact "opposite" of the .test() method!!

In .test() we were passing the string inside the parentheses, while in the .match() we are passing the regex inside the parentheses.
Let's go through a simple example of .match() method:

let extractStr = "Extract the word coding from this string.";
let codingRegex = /coding/; 
let result = extractStr.match(codingRegex); 
console.log(result);

/* output:
 [
  'coding',
  index: 17,
  input: 'Extract the word coding from this string.',
  groups: undefined
]
*/
Enter fullscreen mode Exit fullscreen mode

The above code block shows how the regex coding is extracted from the main string.
The output shows an array of the regex to be matched: coding, the number of the starting index of the word, the main input string and groups which we will discuss later in this blog.

The main difference with .test() method is, the .match() method not only searches the given string but also returns the regex pattern as output.

Try it with your own example!! 🤔

In the next part, we will see a very important concept of REGEX, which is Case Sensitivity.

Discussion (0)