Regular expressions, often abbreviated as regex are patterns used to match character combinations in strings. In the context of JavaScript, regular expressions serve as objects. These patterns are used with the exec()
and test()
methods of RegExp
, and with the match()
, matchAll()
, replace()
, replaceAll()
, search()
, and split()
methods of String
. In today’s blog we will try to discuss in details about Regular Expressions in JavaScript.
What are Regular Expressions?
Regular Expressions (RegeEx) is used for pattern matching or string matching. They are incredibly usaeful for tasks involving search, validation, and manipulation of text. A regex consists of specific characters & symbols that define a search pattern. In JS regEx starts & end with / slash e.g : /regEx/r
Syntax
/pattern/modifiers;
Example
/saqibz/i;
Example explained:
/saqibz/i is a regular expression.
saqibz is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Creating a regular expression
You construct a regular expression in one of two ways:
Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:
const re = /ab+c/;
Or calling the constructor function of the RegExp
object, as follows:
const re = new RegExp("ab+c");