Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
JS. Get part of date from string

I have this string '2020-10-20' Can i somehow get those numbers separately like this:

const [year, month, day] = '2020-10-20'.match(/\d\d\d\d/ what should i write there?)

Or any better approach exist?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can split the string using a delimiter as follows

const [year, month, day] = '2020-10-20'.split("-")

then you would have year=2020 etc.

about 4 years ago · Juan Pablo Isaza Report

0

Using regex you can do something like this:

console.log('2020-10-20'.match(/\d+/g))

If you want to use Array.prototype.split, you can do something like this

console.log('2020-10-20'.split("-"))

about 4 years ago · Juan Pablo Isaza Report

0

I'll add a little bit to the above solutions. If you want to get those values as number then use the map method.

const dateString = "2020-10-12";
const [year, month, date] = dateString.split("-").map(Number);
console.log(year, month, date);

Update

By the way, If you want to learn how to do that with regex, then here's how:

const dateString1 = "2020-10-10";
const dateString2 = "2020/10/10";
const dateString3 = "2020_10_10";

const pattern = /(\d{4}).(\d{2}).(\d{2})/;
 /* 
  * \d - matches digits 0 - 9
  * \d{4} - matches any 4 digits. e.g., 1234, 4587 ...
  * \d{2} - matches any 2 digits.
  * . - matches anything except new line ("\n"). For the
  * separator.
  * (anything-here) - anything inside () is called a capture
  * group.
  * and will be available in the result
  * */
 
 /*
  * console.log(pattern.exec(dateString2))
  * returns [ "2020/10/10", "2020", "10", "10" ]
  * now we need to slice the arrary from index 1 to 3
  * and we get [ "2020", "10", "10" ]
  * */
  
function parseDate(dateString) {
  // For invalid dateString we'll throw an error
  if(!pattern.test(dateString))
    throw new Error("Invalid date string");
  return pattern.exec(dateString).slice(1).map(Number);
}
  
console.log(parseDate(dateString1))
console.log(parseDate(dateString2))
console.log(parseDate(dateString3))

  

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!