DEV Community

Swarnali Roy
Swarnali Roy

Posted on β€’ Edited on

6 2

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

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay