Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Regular expressions

Regular expressions describe text patterns. A RegExp object lets you test for matches and extract parts of text; flags modify how matching works.

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; new RegExp(patternString, flags); regex.test(text); regex.exec(text)

A regular expression describes a pattern rather than a specific string. Create a RegExp object with a /pattern/flags literal or new RegExp(patternString, flags). The constructor is useful for dynamically built patterns. In an ordinary string literal, double the backslash: /\d+/ corresponds to new RegExp("\\d+").

[A-Z] means an uppercase ASCII letter, \d a digit from 0 to 9, and + one or more repetitions. Parentheses (...) capture parts of a match. Without the m flag, the anchors ^ and $ require the beginning and end of the entire string; without anchors, a match may cover only a substring.

test(text) returns a boolean. exec(text) returns an array or null: element 0 is the complete match, and subsequent elements contain captured groups. The i flag ignores case, while g enables successive searches. With g or y, these methods read and update lastIndex, so repeated tests can produce different results. Omit these flags for independent checks.

The regular-expression features used in the example were already available in ECMAScript 5.1, but the const declarations require ECMAScript 2015 or later. The host environment provides console.log; it is not part of ECMAScript. Do not infer browser support for newer regular-expression extensions from a Node.js version.

Examples

const pattern = /^([A-Z]+)-(\d+)$/;
const text = "TASK-42";
const match = pattern.exec(text);
console.log(pattern.test(text));
console.log(JSON.stringify(match === null ? null : match.slice(0, 3)));
console.log(pattern.test("TASK-42!"));

Result

true
["TASK-42","TASK","42"]
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