Skip to content

Instantly share code, notes, and snippets.

@tringuyen1086
Last active March 7, 2022 07:13
Show Gist options
  • Save tringuyen1086/30d169fbbe6b7c99e9ee6f559d94aa81 to your computer and use it in GitHub Desktop.
Save tringuyen1086/30d169fbbe6b7c99e9ee6f559d94aa81 to your computer and use it in GitHub Desktop.
Regex Tutorial - Friendly Guide for Flags

Regular Express (Regex) Tutorial - Friendly Guide for Flags

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

Summary

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');

Table of Contents

Regex

Regex stands for "Regular Expressions." It refers to patterns used to match character combinations in strings.

Regex Creation

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.

Flags

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)

References:

Regular Expressions

Regex tutorial — A quick cheatsheet by examples

Author

Tri Nguyen - Web Developer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment