-1

I have a URL:

http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382

Edit: I should also not the url is stored in a variable and I want it to work something like this:

$(".videothumb a").live('click', function() {
        var URL = < do something to cut the string > 
        console.log(URL);
        return false;
    });

And I want to cut the URL starting from "=" and ending at "&" so I'll end up with a string like this: "JssO4oLBm2s".

I only know of the slice() function but I believe that only takes a number as beginning and end points.

3
  • Sorry, my mistake I just updated. Commented Nov 9, 2013 at 1:31
  • did you try the answers posted below? Commented Nov 9, 2013 at 1:32
  • @KyleJoseph see me answer with fiddle demo Commented Nov 9, 2013 at 1:51

5 Answers 5

1

Using .split() will give a position based solution which will fail the order of parameters changes. Instead I think what you are looking for is the value of parameter called v for that you can use a simple regex like

'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.match('[?&]v=(.*?)(&|$)')[1]
Sign up to request clarification or add additional context in comments.

5 Comments

@Krishna updated to fetch value of v
My url is stored in a variable so this doesn't work.
@KyleJoseph then use the variable like myvar.match('[?&]v=(.*?)(&|$)')[1]
I did and got this error "Uncaught TypeError: Cannot read property '1' of null "
@KyleJoseph it looks like the url don't have the parameter v=?
1

Try

'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'
    .split('=')[1] // 'JssO4oLBm2s&list'
    .split('&')[0] // 'JssO4oLBm2s'

Or, if you want to be sure to get the v parameter,

var v, args = 'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.split("?")[1].split('&');
for(var i = args.length-1; i>=0; --i) {
    var data = args[i].split('=');
    if(data[0]==='v') {  v = data[1]; break;  }
}

Comments

0

Use .split(). Separated to 2 lines for clarity

var first = "http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".split('=')[1]
var result = first.split('&')[0]; //result - JssO4oLBm2s

Comments

0
v = 'JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382';

var vamploc = v.indexOf("&");

vstring = v.substr(0, vamploc);

You can play with the code a bit to refine it, but the general concepts work.

Comments

0

use Regexp (?:v=)(.+?)(?:&|$)

Fiddle DEMO

"http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".match('(?:v=)(.+?)(?:&|$)')[1]


Reference

http://gskinner.com/RegExr/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.