Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

How to use regular expression for string comparison in JavaScript

Akande Olalekan Toheeb

Regular expression

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

Regex have various methods and patterns that they can perform. We will focus on some of these methods and patterns for string comparison in this shot.


Although there are various regex methods, we will use two regex methods to perform string comparison.

  1. .test(): This is a method that takes a regex, applies it to a string placed inside the parenthesis, and returns true or false depending on whether the conditions are met or not. We use the string pattern regex in this shot. 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 takes a string and the regex is passed into the parenthesis of the .match().


Let’s suppose we want to compare the string “Bird” using the regex method. This can be done as demonstrated below.



  • Line 1: We create a variable and assign it to a string.

  • Line 2: We create a regex and input bird to it. The input is all in lower case. The g in this line is a regex flag that lets us match a pattern if it occurs more than once in a string. If the string inside the regex matches the string we are testing then it will all be extracted. The i in this line is another regex flag that ignores the letter case.

  • Line 3: We create a variable. We use the .match() method to compare the string and extract it and assign the result to this variable.

  • Line 4: In case the match is found, the variable result will be printed to the console.



Akande Olalekan Toheeb

View all Courses

Keep Exploring