0

I have a string like this:

http://x.com/xyz/2013/01/16/zz/040800.php

I want to get two strings from that, like this:

2013-01-16 <-- string 1
04:08:00 <-- string 2

How can I do that?

5
  • are your strings everytime of the same format? Commented Jan 16, 2013 at 14:23
  • yes. "x.com", "xyz" and "zz" are constant. others variable. Commented Jan 16, 2013 at 14:24
  • w3schools.com/jsref/jsref_obj_regexp.asp and w3schools.com/jsref/jsref_obj_string.asp Commented Jan 16, 2013 at 14:25
  • @SunnyTAR if you click help on the right side of the comment box, you can see how to add links to comments Commented Jan 16, 2013 at 14:25
  • @bart s I am on my way. testing) Commented Jan 16, 2013 at 14:26

2 Answers 2

2

You can use regulax expressions. Here is a sample solution:

var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
    result = parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"

This will work if your domain is .com and you have just one extra parameter before the date.

Let me explain you the regular expression:

 /          //starts the regular expression
 .com       //matches .com
   \/       //matches /
   [^\/]+   //matches anything except /
      \/    //matches a single /
      (\d+) //matches more digits (one or more)
      \/    //matches /
   (\d+)    //matches more digits (one or more)
  \/        //matches /
 (\d+)      //matches more digits (one or more)
/           //ends the regular expression

Here is how you can extract the whole data:

var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)\/[^\/]+\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
    part2 = parts[4];

parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"
part2[0] + part2[1] + ':' + part2[2] + part2[3] + ':' + part2[4] + part2[5];
Sign up to request clarification or add additional context in comments.

1 Comment

Just updated my answer and included information about that how you can extract the second value too :-)
1

If the url is always of the same format, do this

var string = 'http://x.com/xyz/2013/01/16/zz/040800.php';

var parts = string.split('/');

var string1 = parts[4] +'-' +parts[5] +"-" +parts[6];
var string2 = parts[8][0]+parts[8][1] +":" +parts[8][2]+parts[8][3] +":" +parts[8][4]+parts[8][5];

alert(string1);
alert(string2);

DEMO

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.