Regular Expression Flags

In the previous article, you learned about regular expression being pattern of search. Regular expression uses flags that are optional and perform searches that are global or case-insensitive. You can use these searches separately or together to do search.

Advertisements

List of Flags

Here is a list of flags commonly used with regular expressions.

FlagMeaning
icase-insensitive
gglobal search
m multi-line search
utreat a pattern as Unicode code
sA.B is a pattern where any character is allowed instead of “dot” except “\n”. s flag allows even
y“sticky” search, means start from a current position in the string.
flags in regular expression

The syntax to use a pattern with flags is as follows.

/pattern/flags

i – Case insensitive

The i flag is case-insensitive and ignore any upper or lowercase text for string search. For example, A or a are same in this search.

Example #1

var myStr = " He is very intelligent person and he reads lot of books";
var value = myStr.match(/he/i);
alert(value);

Output #1

The i flag will ignore the capital ‘H’ in He

In the example above, the i flag will match with “He” and ignore the capital “H” immediately. Therefore, pattern match is successful.

g – Global

Advertisements

Usually the search pattern will stop right after the first match, but you can continue the search for whole string if the global flag is used. You may also use this flag with other flags such as i.

Example #2

var myStr = " The red van is parked around the corner. I like Red vehicles like that only.";
var value = myStr.match(/red/ig);
alert(value);

The search does not stop at the first instance of “red” and also, it is case-insensitive. Finally, all word that spell “red” are matched successfully.

Output #2

All instance of “red” are matched

m – multiline

When the sting span multiple line then to search a sub-string the pattern can include the m flag with other flags.

var myStr = " Cricket is a great sport. I play cricket 
regularly and our team win matches";
var value = myStr.match(/cricket/igm);
alert(value);

The string about is started from a new line to complete the sentence. The search in this case could not find anything assuming that the line is incomplete. Therefore, a m flag will allow it to complete the search even in the next line.

Output #3

All instance are located including the next line

The rest of the flags will be discussed in more details when we talk about character classes.

Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version