Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Regular expression literal

A regular expression literal (RegExp literal) writes a pattern directly in code as /pattern/flags. It creates a RegExp object that can be used to test text, search for matches, or replace matching text.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

/pattern/flags

A RegExp literal has the form /pattern/flags, without quotation marks. The slashes delimit the pattern, and optional flags change matching behavior. Each evaluation of a literal creates a new RegExp object, even when its contents remain unchanged.

In the example, ^ marks the start of the text, $ its end, and \d+ one or more ASCII digits. The i flag ignores letter case. The test() method returns a Boolean. Without the g and y flags, successive calls do not advance the search position through lastIndex.

A literal does not require the backslash doubling needed in strings: /\d+/ corresponds to new RegExp("\\d+"). The constructor allows a pattern to be built from text at runtime. To match / outside a character class, write \/. Do not place a raw line terminator inside a literal; use an escape such as \n. The sequence // starts a comment rather than an empty pattern; an empty pattern can be written as /(?:)/.

An invalid literal pattern or invalid flags cause a SyntaxError before code execution. Flags cannot be repeated, and u and v are mutually exclusive. Support for newer flags depends on the engine; the example uses neither such extensions nor browser APIs.

Examples

const pattern = /^item-\d+$/i;
console.log(pattern.test("ITEM-42"));
console.log(pattern.test("item-x"));

Result

true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources