user1389646
user1389646

Reputation: 132

Extract Part of URL JS

How could I extract just the date part from the following string?

var string = "http://www.blah.co.uk/world/images/landing-pages/furniture/11-12-2015/furniture.jpg"

The "furniture.jpg" part will be variable length as well as the furniture department text before the date.

Thank you, D

Upvotes: 0

Views: 641

Answers (3)

Zac Braddy
Zac Braddy

Reputation: 611

You could use this regex

var string = "http://www.blah.co.uk/world/images/landing-pages/furniture/11-12-2015/furniture.jpg";
var iWantThisDate = /[0-9]+-[0-9]+-[0-9]+/.exec(string);

That would get you just the date pattern out of the string and put it in iWantThisDate.

Upvotes: 0

Farnabaz
Farnabaz

Reputation: 4066

String has a great function match, you can pass regex (regular expression) to it and this return matches in string

var string = "http://www.blah.co.uk/world/images/landing-pages/furniture/11-12-2015/furniture.jpg"
string.match(/\d{2}-\d{2}-\d{4}/) // out: ["11-12-2015"]

if you interest in regular expression look at MDN

Upvotes: 2

andrrs
andrrs

Reputation: 2309

Can you perhaps split by "/" and take the second to last?

var components = string.split("/");
var dateString = components[components.length - 2]

Upvotes: 1

Related Questions