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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
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.
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.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.
'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
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.s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').(a+)+$ on long input can freeze the app (ReDoS). Avoid nested quantifiers on untrusted input.Try patterns live in the regex tester.