Regex : .test() , .match(), Flags ..... SIMPLIFIED

Regex : .test() , .match(), Flags ..... SIMPLIFIED

ยท

5 min read

Regular Expressions

Regex or Regular Expressions are patterns which are helpful in matching, searching or replacing some text/parts of a text. For example :

let str = "He has 12 oranges and 10 apples.";
/*In the above string str, we can search for every occurrence of a digit, or , 
replace 12 and 10 with some other number. 
In short, the pattern here, is the numeric data. */

Regex is just a way to operate on such (more complex)patterns.

Syntax :

We are going to go with the short syntax here (Hit up google for the longer one guys ;-) ) :

let regexsyntax = / pattern /;
/*slashes indicate that we want to create a new regexp 
which is the new instance of the class RegExp. */

The short syntax is used when we are already aware of the regular expression.

Test & Match :

//testing if a character M exists in the string str.....
let str = "My name is ...."
let myRegex = /M/;
let res = myRegex.test(str);   
console.log(res);       //returns True

.test() method is used to check whether a certain pattern is present in the given string or not. It returns either True or False.

Whereas .match() method checks the presence of particular pattern and returns the match findings as well , for instance :

let str = "My name is ...."
let myRegex = /M/;
let res = str.match(myRegex);   
console.log(res);

/*Result : [ 'M', index: 0, input: 'My name is ....', groups: undefined ]
Shows the matched character M , its index 0 and 
the string in which it was searched for. */

If you observe, syntaxes for .match() and .test() are the reverse of each other :

//for .test()
regexpattern.test(string)

//for .match()
string.match(regexpattern)

Now that we have been introduced to the basic syntax and the 2 methods, let's jump to an important part of regex : Flags.

Flags :

You can think of Flags as properties which give an extra touch to the patterns.

Flags can enable the search to continue even after encountering the first successful match (global flag) OR make the search case(lower or uppercase) insensitive (case insensitive flag) etc etc...............

//Syntax  :
let myRegex = /pattern/flag ;

Let's have a quick glance at some of the flags :

  • i : The case insensitive Flag
let str = "my name is ...."
let myRegex = /M/i;
let res = str.match(myRegex);   
console.log(res);

//Result : [ 'm', index: 0, input: 'my name is ....', groups: undefined ]

Even though we mentioned the letter M in uppercase, the search stops at index 0 which is a lowercase m. This happens because of the i flag mentioned after the regex which searches for the character mentioned irrespective of its case.

  • g : The global flag
let str = "my name is ...."
let myRegex = /m/g;
let res = str.match(myRegex);   
console.log(res);

/*Result : [ 'm', 'm' ]     
an array of all the successful matches are returned in .match() method.*/

In the absence of the global flag, the search is stopped as soon as a successful match is found or no match is found. The global flag extends the pattern search to the whole text/string even after finding the first match of the pattern. Hence, here we achieved an array of 2 m's rather than just one.

  • m : Multiline mode

This flag is used only when the start/end of a string is concerned. The start of a string is indicated by ^ symbol while $ signifies the end part. Let's look at an example :

let str = `Is there anyone who
is not 
scared`        // `.......... ` is used to write multiline text

let myRegex = /^is/m;    //finding "is" as the start of a text
let res = str.match(myRegex);   
console.log(res);

/*result : [ 'is', index: 20, input: 'Is there anyone who\nis not \nscared', 
groups: undefined ]
newline char \n is counted as well, depicting a multiline string */

As you can see, the input string : 'Is there anyone who\nis not \nscared' is considered as multiline here. Since we have used the m flag, it searches for is at the start of each line separately. Since \n is considered as a character in the input, the index of is becomes 20.

Similarly we can search for a word at the end of each line say, /scared$/. This will return the index of the word scared at the last line of the string.

  • s : DotAll modifier

Before knowing about this flag, one must know that a dot in regex represents every possible character except a newline character \n. Hence, if we write say, /C.t/ and test it with a string "Cat" or "C#t" or "Cut" or "C!t", it will return true for all these but not for "C\nt".

For such cases, we use the s modifier which makes the dot character include \n as well.

let str = "A\nB"
let myRegex = /A.B/s;
let res = str.match(myRegex);   
console.log(res);

/* result : [ 'A\nB', index: 0, input: 'A\nB', groups: undefined ] */

With this, we conclude our blog today. It was an effort to summarize all the mentioned topics in the most simplified way with some examples.

I hope the concepts were explained clearly. If you have any doubts, feel free to reach out or comment.

Ciao Folks!!

Have a nice day ๐Ÿ˜„

Did you find this article valuable?

Support Sonakshi Tyagi by becoming a sponsor. Any amount is appreciated!

ย