How to access matched groups in JavaScript regular expression?
Hello everyone! I'm a beginner in JavaScript and working with regular expressions. I have a string, for example, `"Today 25.12.2023"`, and I want to extract the day, month, and year separately. I wrote this code:\n\n```javascript\nlet str = "Today 25.12.2023";\nlet regex = /(\\d{2})\\.(\\d{2})\\.(\\d{4})/;\nlet result = regex.exec(str);\nconsole.log(result);\n```\n\nIn the console I see an array, but I don't understand how to get exactly the day, month, and year. I tried writing `result[1]`, `result[2]`, `result[3]` — it works, but it seems not very convenient to me. Also, if I use `str.match(regex)`, the result is different when there are no matches.\n\nPlease explain how to properly access capture groups in JavaScript? In which cases should I use `exec()`, and in which `match()`? And can I
No answers yet.
Log in to leave an answer
Blogs