Regular expressions (Regex) are patterns that are used to match character combinations in strings. In this tutorial, we will discuss about the advanced searching with flags
Regex provides users with optional flags that can be functional as global searching and case-insensitive searching.
To include a flag with the Regex, the following syntax is used:
const re = /pattern/flags;
An alternative option for this syntax:
const re = new RegExp('pattern','flags');
Regex stands for "Regular Expressions." It refers to patterns used to match character combinations in strings.
Regex can be created in two methods:
Method 1: using a regular expression literal consisting of a pattern enclosed between slashes:
const re = /ab+c/;
As the script is loaded, Regex literals add compilation of the regular expression. This can be used to improve performance if the Regex remains constant.
Method 2: Calling the constructor function of the RegExp
object:
const re = new RegExp('ab+c');
The constructor function adds runtime compilation of the regular expression. When we know the regular expression will be changing, or don't know the pattern and getting it from another source (e.g. user input), the constructor function method is recommended.
A Regex usually appears within this form /abc/
. In this form, the search pattern is delimited by 2 slash characters /
. We can specify a flag with these values or combine them at the end:
Flag | Description | Corresponding Property |
---|---|---|
d |
Generate indices for substring matches | RegExp.prototype.hasIndices |
g |
Global search | RegExp.prototype.global |
i |
Case-insensitive search | RegExp.prototype.ignoreCase |
m |
Multi-line search | RegExp.prototype.multiline |
u |
"unicode"; treat a pattern as a sequence of unicode code points | RegExp.prototype.unicode |
y |
Perform a "sticky" search that matches starting at the current position in the target string | RegExp.prototype.sticky |
Notes
- g (global) restart the subsequent searches from the end of the previous match. It won't return after the first match.
- m (multi-line) will match the start and end of a line, instead of the whole string when
^
and$
are enabled. - i (insensitive) results in the whole expression case-insensitive (e.g. /xYz/i would match XyZ)