MediumModern JS📖 Theory Question

What are the basics of regular expressions in JavaScript?

💡

Hint

Pattern matching: literal chars, character classes, quantifiers, groups, flags (g, i, m)

Full Answer

// Creating regex
const r1 = /hello/;           // literal
const r2 = new RegExp('hello'); // dynamic pattern

// Test & match
/hello/.test('say hello');  // true
'hello world'.match(/\w+/g); // ['hello', 'world']
'hello world'.match(/(\w+)\s(\w+)/); // with groups

// Character classes
/[aeiou]/     // any vowel
/[^aeiou]/    // NOT a vowel
/[a-z]/       // lowercase letter
/\d/          // digit [0-9]
/\w/          // word char [a-zA-Z0-9_]
/\s/          // whitespace
/./           // any char except newline

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

// Anchors
/^hello/      // starts with
/world$/      // ends with

// Groups
/(\d{4})-(\d{2})-(\d{2})/.exec('2024-01-15');
// groups: ['2024', '01', '15']
/(?<year>\d{4})-(?<month>\d{2})/.exec('2024-01');
// Named: match.groups.year, match.groups.month

// Lookahead / lookbehind
/\d+(?= dollars)/   // digits followed by " dollars"
/(?<=\$)\d+/        // digits preceded by $
/\d+(?! dollars)/   // digits NOT followed by " dollars"

// Flags
/pattern/g   // global — find all matches
/pattern/i   // case insensitive
/pattern/m   // multiline — ^ and $ match line starts/ends
/pattern/s   // dotAll — . matches newline too

// Common operations
'a1b2'.replace(/\d/g, '#');    // 'a#b#'
'a,b,,c'.split(/,+/);          // ['a','b','c']
'hello'.search(/e/);            // 1 (index)
💡 Greedy vs lazy: /a.*b/ greedily matches as MUCH as possible; /a.*?b/ lazily matches as LITTLE as possible. Add ? after quantifiers for lazy: +?, *?, {n,m}?

More Modern JS Questions

MediumWhat are generators and when would you use them?→EasyWhat is optional chaining (?.) and nullish coalescing (??)?→EasyWhat are tagged template literals and what are they used for?→EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint