DEV3 Technologies home

DEV3 Developer Forum

How do I write a JavaScript regex to match and extract parts of a string safely?

JavaScript helpSolved0 views
dev3 ·

I need to extract the year, month and day from '2025-03-10' and also replace all occurrences of a word. I keep getting only the first match. How do regex flags and named groups work?

#javascript#regex#strings

0

1 reply

dev3 · Accepted answer

Named groups and match

const m = '2025-03-10'.match(/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/);
if (m) {
  const { year, month, day } = m.groups;
}

Anchors ^/$ make sure the whole string matches.

Flags

  • g global: all matches (needed for replace of every occurrence).
  • i case-insensitive.
  • m multiline: ^/$ per line.
  • s dot matches newlines.
  • u Unicode aware (use it with emoji, \p{L}).
  • y sticky.

All matches

const text = 'a1 b22 c333';
for (const m of text.matchAll(/(?<letter>[a-z])(?<num>\d+)/g)) {
  console.log(m.groups.letter, m.groups.num, m.index);
}

matchAll requires the g flag and returns an iterator.

Replace

'foo foo'.replace(/foo/g, 'bar');      // 'bar bar'
'foo foo'.replaceAll('foo', 'bar');    // string version, no regex needed
'John Smith'.replace(/(\w+) (\w+)/, '$2, $1');          // numbered
'x'.replace(/x/, (match) => match.toUpperCase());       // function

Pitfalls

  1. regex.test() with the g flag keeps lastIndex between calls and alternates true/false. Do not reuse a global regex for test, or reset lastIndex = 0.
  2. Build regexes from user input only after escaping: s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').
  3. Catastrophic backtracking: patterns like (a+)+$ on long input can freeze the app (ReDoS). Avoid nested quantifiers on untrusted input.
  4. Do not validate emails or HTML with a regex alone; check basic shape and verify by sending mail.

Try patterns live in the regex tester.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.