bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Working with Data
JavaScript•Working with Data

JavaScript RegExp

Regular Expressions

A Regular Expression is a sequence of characters that forms a search pattern. Regex is a common shorthand for a regular expression.

RegExp is an

Object for handling Regular Expressions.

RegExp are be used for:

Text searching

Text replacing

Text validation

Example

Formula

Do a case - insensitive search for "w3schools" in a string:
let text = "Visit W3Schools";
let n = text.search(/w3schools/i);

Example explained:

Formula

/w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

Formula

i is a modifier (modifies the search to be case - insensitive).

Regular Expression Syntax

/ pattern / modifier flags

;

Using String Methods

Regular expressions are often used with the string methods

Method

Description match(

regex )

Returns an Array of results replace(

regex )

Returns a new String search(

regex )

Returns the index of the first match

Using String match()

Search for "W3schools" in a string:

let text = "Visit W3Schools";
let n = text.match(/W3schools/);

Using String replace()

Replace Microsoft with W3Schools in a string:

let text = "Visit Microsoft!";
let result = text.replace(/Microsoft/i, "W3Schools");

Using String search()

Search for "W3Schools" in a string:

let text = "Visit W3Schools";
let n = text.search(/W3Schools/);
RexExp Alternation (OR)

In a regular expression an alternation is denoted with a vertical line character |. An alternation matches any of the alternatives separated with |.

Example

A global search for the alternatives (red|green|blue):
let text = "Black, white, red, green, blue, yellow.";
let result = text.match(/red|green|blue/g);

JavaScript Regex Flags

/pattern/ flags

Regular expression flags are parameters that can modify how a pattern is used, such as making it case-insensitive or global.

These are the most common:

Flag

Description

/g Performs a global match (find all) /i

Performs case-insensitive matching

/u Enables Unicode support (new 2015)

Formula

The /g Flag (Global)

Previous

JavaScript Math Object

Next

JavaScript String Templates