0

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

1
  • string.lastIndexOf("/") or split("/") .. and move your way from there... Commented Nov 11, 2015 at 15:19

3 Answers 3

2

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

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

4 Comments

I prefer this answer because it doesn't alway has to be in the same place of the url, just match the date format, nice
It's also less efficent than the substring @Thomas
For something like this efficiency is a low priority.
@Liam I prefer security over some milliseconds performance gain
1

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

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

7 Comments

@Liam Since the array is zero-indexed, components[components.length] would be out of the array and components[components.length - 1] would be "furniture.jpg"
Ignore me, brain not firing on all cylinders... this is the answer
Whilst this works, it relies on the string being in a certain structure. That may or may not be a problem depending the context of the problem @user1389646 is trying to solve. Personally, I would prefer not to couple my code the the structure of the URL in this way.
But will it be possible at all to answer this question without making assumptions? Farnabaz solution is neat but again that assumes the url only has one date in it. Perhaps a safer assumption, perhaps not, but still an assumption.
But parsing strings is always coupled to a certain structure. Your answer @ZacBraddy is no different, it relies on data being a in a certain place in the string. If the the OP wants the second to last part of the URL then this does it and you could argue a RegEx is simply in-efficent/goldplating
|
0

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.

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.