How to Extract a Date from a String in JavaScript?

Estimated read time 1 min read

To extract a date from a string in JavaScript, you can use regular expressions or a library like Moment.js. Here are some examples:

Using Regular Expressions:

const string = "The event happened on 2022-11-23";
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const match = regex.exec(string);
if (match) {
  const year = match[1];
  const month = match[2];
  const day = match[3];
  const date = new Date(year, month - 1, day);
  console.log(date); // output: Wed Nov 23 2022 00:00:00 GMT+0000 (Coordinated Universal Time)
}

In the above example, the regular expression /(\d{4})-(\d{2})-(\d{2})/ matches a date string in the format of “YYYY-MM-DD”. We use exec() method to find the match and then create a new Date object with the extracted year, month, and day.

Using Moment.js:

const string = "The event happened on 2022-11-23";
const date = moment(string, "YYYY-MM-DD").toDate();
console.log(date); // output: Wed Nov 23 2022 00:00:00 GMT+0000 (Coordinated Universal Time)

In the above example, we use Moment.js library to parse the date string using the format “YYYY-MM-DD” and convert it to a JavaScript Date object using the toDate() method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply