DEV Community

Dhairya Shah
Dhairya Shah

Posted on

How to extract year from a string

Hello Folks 👋

What's up friends, this is SnowBit here. I am young passionate and self-taught developer and have an intention to become successful developer.

Today, I am here with a quick tutorial. So, let's get started.

Extracting year from a string

Let use take a date,

24 February 2006
Enter fullscreen mode Exit fullscreen mode

Now, we have to extract year from the string, so here's how you do it

const extractYear = str => str.match(/\d{4}/)[0];
Enter fullscreen mode Exit fullscreen mode

Works with any layout of date

const extractYear = str => str.match(/\d{4}/)[0];


console.log(extractYear("24 February 2006"))
console.log(extractYear("24-02-2006"))
console.log(extractYear("24/02/2006"))
Enter fullscreen mode Exit fullscreen mode

Try Now,


Thank you for reading, have a nice day!
Your appreciation is my motivation 😊

Top comments (0)