Regular expression flag or modifier # 03

We can represent regular expression flags or modifiers in two ways …

1. With Regular expression literals ...

const regexp = /pattern/; // no flags

const regexp = /pattern/gmi; // with flags g,m and i


2. Call the constructor of regular expression to create a regular expression object ...

const regexp = new RegExp("pattern", "flags");


Flags

Regular expressions may have flags that affect the search.

There are only 6 of them in JavaScript:

i

By default regular expression is case sensitive. With this flag, the search is case-insensitive: no difference between A and a (see the example below). Capital letters and small letters will be considered the same.

g

With this flag, the search looks for all matches, without it – only the first match is returned.

m

Multiline mode (covered in the chapter Multiline mode of anchors ^ $, flag "m").

s

Enables “dot all” mode, which allows a dot . to match newline characters \n (covered in the chapter Character classes).

u

Enables full Unicode support. The flag enables the correct processing of surrogate pairs. More about that in the chapter Unicode: flag "u" and class \p{...}.

y

“Sticky” mode: searching at the exact position in the text (covered in the chapter Sticky flag "y", searching at position)


Post a Comment

Previous Post Next Post