1

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.

2
  • 2
    Remove \s+ and add /g modifier - txt.match(/\d{4}-\d{2}-\d{2}/g). You may add word boundaries \b if you need a "whole word" match. Commented Nov 15, 2017 at 7:52
  • :) thank very much . Commented Nov 15, 2017 at 7:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.