You are currently viewing 4 Best Examples of Using Regex with Match() Method in JavaScript

4 Best Examples of Using Regex with Match() Method in JavaScript

JavaScript Regex Match Example

In this article, we will see the some example using regex and match() method together in JavaScript.

What is a regular expression and how to use it?

A regular expression in javascript is an operation using special characters, characters, and numbers. The short form of the regular expression is ‘regex’ or ‘regexp’. It forms a search pattern by using a sequence of characters like ‘\W, ^,’. It is used to match patterns within strings in a flexible and efficient way. So, in JavaScript, the regex does many things like performing pattern matching and text manipulation functions.

Creating regex literal: We can use the regular expression literal to check whether specific word matches or not. If we put a forward slash ‘/’ at the beginning and end of a word like ‘/hello/‘, the word becomes a regular expression. For ex:

const myRegex = /hello/;

In this example code, we have created the constant variable called ‘myRegex’ and assigned it to the regular expression ‘/hello/’. It will match the exact string “hello” in any given string.

So, we can use this regular expression in different ways, such as with the ‘test’ method to check if a string matches the pattern, with the ‘match()’ method to extract the matching substring from a larger string, or with ‘replace()’ method to replace the matching substring of a string. We can By mastering regular expressions, you can perform complex pattern matching and text manipulation operations with ease.

What is the match() method?

The ‘match()’ method is a built-in function and it allows you to search for a specified pattern within a string using a regular expression. For example:

string.match(myRegex)
  • In this above example, we should have stored ‘string values’ in the ‘string‘ variable
  • The ‘regexp‘ is the regular expression. We should have stored the word you want to match in the ‘myRegex‘ variable
  • The match() method returns an array of all matches that are found. If the regular expression includes capturing groups, then the array will also include the captured substrings.

Why do we use the regex and match() methods together?

We can easily find occurrences of a particular substring in a string by using the regex and match() method together. And often used to perform complex string operations by using regex and match() methods, such as:

  • Validation of user input: We can check if the user input matches a specific pattern, such as an email address, phone number, or password.
  • String manipulation: If we store the string as a sentence or paragraph in a variable, we can find and replace specific parts of a string, or split a string into an array based on a delimiter.
  • Data extraction: We can also extract specific data or substring from a string using regular expressions and the .match() method. For example, you might extract all the URLs from a block of text or all the phone numbers from a list of customer records.
READ ALSO  How to Find Character in String JavaScript | Step by Step Guide

Examples of regex with the match() method

1. Matching a specific word in a string

In this method, we are going to check whether a string has a specific substring or not. If the string has a substring that we check, it returned that substring otherwise the ‘null’ value is returned

const string = "My dad never works on the weekends";

const regex = new RegExp("dad");
const result = string.match(regex);
document.write(result);

// Output: dad
  • In this above example, we have created the variable called ‘string‘ and it has some string value.
  • Then we create a regular expression pattern using ‘new RegExp()‘ in the variable ‘regex’. We have to pass the substring we want to check as an argument to the RegExp() constructor. In this case, we passed the word ‘dad‘.
  • Then we pass the regular expression pattern to the ‘match()’ method to search for the word ‘dad‘ in the ‘string variable.
  • Finally, print the variable ‘result’ using the document.write() method.

Since there is only one match for the word “dad” in the variable ‘string’, so the match() method returns the value, which is “dad”.

2. Matching multiple occurrences of a word in a string

In this method, we see example of using javascript regex and the match method to find how many times a particular substring/word occurs in a string. The substring will be returned as how many times as there are occurrences of the substring in the string. For example:

const string = "The quick brown fox jumps over the lazy fox .";
const word = "fox";
const regex = new RegExp(word, "g");
const result = string.match(regex);
console.log(result);

// Output: ["fox", "fox"]
  • In this above code, we have created a regular expression pattern using ‘new RegExp(word, “g”)‘, where the “g” flag tells the regular expression to search for all matches in the string.
  • Then we pass this regular expression pattern to the match() method to search for all occurrences of the word “fox” in the ‘string’ variable.
READ ALSO  How to Create Custom Alert Box in Javascript | Easy Method

So, here we have two occurrences of the word “fox” in the string, so the match() method returns an array with two elements, both of which are “fox”.

3. Matching a string with optional characters:

In this method, we check whether a string has a specific substring with optional characters. To specify optional character in the string, we need to put the ‘?’ question mark after that character. Example of a string with optional characters is “/colou?r/“, “behaviou?r“. So, the advantage of an optional character is whether if the optional character occurs or not in place of ‘before the question mark’, it will match.

const string1 = "My favourite colour is blue.";
const string2 = "The color of the text is green.";

const regex = /colou?r/;
const result1 = string1.match(regex);
const result2 = string2.match(regex);

console.log(result1); // Output: ["colour"]
console.log(result2); //Output : ["color"]
  • In this above example, we have created two variables called ‘string1’ and ‘string2’. Both variables have string values, specifically the ‘string1’ has ‘colour‘ value and string2 has ‘color‘. So, we can use a single regular expression with an optional character to search whether ‘colour’ and ‘color’ words are in a string.
  • Then we created a regular expression pattern using /colou?r/, which searches for a string that contains the word “color” or “colour”. The “?” in the regular expression pattern makes the “u” optional, so the pattern matches both “color” and “colour”.
  • Then pass this regular expression pattern to the ‘match()’ method to search for the word “color” or “colour” in the variable.

Since there is one match for each word, the match() method returns an array with one element for each match, which are “color” and “colour”.

4. Matching a string with a specific format (such as a phone number):

In this method, we check whether a string has a specific format number. The format of US, Canada, and other NANP (North American Numbering Plan) countries’ phone numbers is three-digit followed by four-digit. So, if there is any number in the format of ‘XXX-NNNN’ then it will return otherwise the value ‘null’ will be returned.

const str = "John's phone number is 555-1234.";
const regex = /\d{3}-\d{4}/;
const result = str.match(regex);
console.log(result); // Output: ["555-1234"]
  • In this example, we created the variable ‘str’ and assigned it to a string value with numbers.
  • Then we create a regular expression pattern in the variable ‘regex’ by using /\d{3}-\d{4}/, which searches for a string with the format of a phone number format, i.e. “555-1234”.
  • We pass that regular expression pattern to the match() method in the variable ‘result’ to search for the phone number in the ‘str’ variable.
  • Finally, we logged the variable ‘result’ and it contains the match

So, there is only one phone number in the variable ‘str’, the match() method returns an array with one element, which is the phone number “555-1234”.

Conclusion

So, we can do examples like this using regular expression i.e regex with match method in javascript.

Leave a Reply