JS RegExp

Regular expressions are used for pattern matching in text. Learn how to test and search strings with RegExp.

On this page

JS RegExp

Regular Expressions (RegExp) are patterns used to match character combinations in strings.

const pattern = /js/i;
console.log(pattern.test("JavaScript")); // true

JS RegExp Flags

Flags modify how a pattern behaves.

/g  // global
/i  // case-insensitive
/m  // multiline
/s  // dotAll (dot matches newline)
/u  // unicode
/y  // sticky
const text = "JS js Js";
console.log(text.match(/js/gi));

JS RegExp Classes

Character classes match sets of characters.

/[abc]/      // a or b or c
/[0-9]/      // digits
/[A-Z]/      // uppercase letters
/d/         // digit
/w/         // word character
/s/         // whitespace

JS RegExp Metachars

Metacharacters have special meaning.

.   // any character except newline
^   // start of string
$   // end of string
|   // OR
()  // grouping
[]  // character set
{}  // quantifier

JS RegExp Assertions

Assertions check positions without consuming characters.

^Hello     // starts with Hello
world$     // ends with world

Lookahead and lookbehind:

/d(?=px)/      // digit followed by px
/(?<=$)d+/    // digits after $

JS RegExp Quantifiers

Quantifiers define how many times a pattern must appear.

a+   // one or more
a*   // zero or more
a?   // zero or one
a{3} // exactly 3
a{2,5} // between 2 and 5

JS RegExp Patterns

Common practical examples:

Remove extra whitespace:

const text = "Hello     JS";
console.log(text.replace(/s+/g, " "));

Slug normalization:

function slugify(str) {
  return str
    .toLowerCase()
    .replace(/s+/g, "-")
    .replace(/[^a-z0-9-]/g, "");
}

console.log(slugify("JS RegExp Guide!"));

Named capture groups:

const date = "2026-02-13";
const match = date.match(/(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/);

console.log(match.groups.year);

JS RegExp Objects

You can create regex using literal or constructor syntax.

const r1 = /js/i;
const r2 = new RegExp("js", "i");

JS RegExp Methods

RegExp and String both provide useful methods.

const text2 = "Learn JS easily";

console.log(/JS/.test(text2));
console.log(text2.search(/JS/));
console.log(text2.match(/JS/));
console.log(text2.replace(/JS/, "JavaScript"));

matchAll() returns all matches including capture groups.

const str = "1 apple, 2 oranges";
const matches = str.matchAll(/d+/g);

for (const m of matches) {
  console.log(m[0]);
}

Next Step

Continue with JS Data Types to understand primitive and reference values in JavaScript.

JS RegExp Examples (8)