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.
.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.
.match(): This is the opposite of
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
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.
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.
View all Courses