Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2050

Extract dates with javascript and regExp

I have a string txt='2017-04-01 and 2017-04-04' and i need to get the dates from the string. I've tried with txt.match(/(\d{4})-(\d{2})-(\d{2})\s+/) but i get:

[
  "2017-04-01 ",
  "2017",
  "04",
  "01"
]

off course that i need

[
      "2017-04-01",
      "2017-04-04"
    ]

Thanks.

Upvotes: 1

Views: 37

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

The last \s+ requires 1+ whitespaces but the last date is at the end of the string. You may remove \s+ or require a word boundary \b (may be both at the start and end of the pattern). To get all matches, add /g (global) modifier:

txt='2017-04-01 and 2017-04-04';
console.log(txt.match(/\b\d{4}-\d{2}-\d{2}\b/g));

I removed the capturing groups since you are not expecting those details in your output. If you do, you will need to add them back and use a RegExp#exec in a loop to get all the necessary substrings.

Upvotes: 1

Related Questions