How to use regular expression for string comparison in JavaScript

Share

Regular expression

Regular expressions in JavaScript are used to perform various operations. The operations include matching, searching, and replacement of strings or texts in development. They are also referred to as regex.

Regex has various methods and patterns that can be used. We will focus on some of the methods and patterns for string comparison in this answer.

Methods

Although there are various regex methods, we will use the following two methods to perform string comparisons.

  1. .test(): This method is called against a regex, takes a string to be tested on the regex as a parameter, and returns true or false depending on whether the conditions are met or not. We use the string pattern regex in this answer. If the string matches, it will return true.

  2. .match(): This is the opposite of test(). This is a regex method that lets us extract the string after its existence has been confirmed. It is called against the string and the regex is passed as a parameter to match().

Example

Let’s suppose we want to compare the string bird using the match() and test() method. This can be done as demonstrated below.

var myStr = "Bird";
var myRegex = /bird/gi;
//Using Match()
var result = myStr.match(myRegex);
console.log(result);
//Using test()
var result = myRegex.test(myStr);
console.log(result);

Explanation

  • Line 1: We create a string variable.

  • Line 2: We create a regex with a bird pattern. The input is in lowercase. The g in this line is a global match flag that lets us match a pattern if it occurs even more than once in a string. If the string matches the regex it will return all the matched ones. The i in this line is a case-insensitive flag that ignores the letter case.

  • Line 5: We create a variable result. We call the match() method to compare the string and store the returned information in the result variable.

  • Line 6: The result variable will be printed to the console.

  • Line 9: We create a variable result. We call the test() method to compare the string and store the returned information in the result variable.

  • Line 10: A Boolean value will be printed to the console.

Copyright ©2024 Educative, Inc. All rights reserved