Little help with javascript SPLIT

Discussion in 'JavaScript' started by kuser, Dec 20, 2012.

  1. #1
    So, i know the PHP explode function for Javascript is the split function.

    So, If I am doing something like:

    var temp = youtubeurl.split("?v=");

    1. How can I check if temp[1] was made or not?!

    2. How I can count the temp[] elements ?!
     
    kuser, Dec 20, 2012 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    If temp has a length of less than 2, it wasn't.
    temp.length;
     
    Rukbat, Dec 20, 2012 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I would suggest not using SPLIT for that -- or at least not just one SPLIT since it's possible the GETDATA in the URL may not have v= as the first parameter.

    I would first separate out just the hash onward... then split it by ampersand... then search through that result set for the desired param. Probably put that in a function so you can re-use it for other parameter searches too.

    
    function getParamFromURL(searchURL,searchParam) {
    	var offset=searchURL.indexOf('#');
    	if (offset>=0) {
    		var hash = searchURL.substr(offset+1);
    		var getParams = hash.split('&');
    		for (var t=0; t<getParams.length; t++) {
    			var param = getParams[t].split('=');
    			if (param[0] == searchParam) return (param[1] ? param[1] : -1);
    		}
    	}
    	return -1; // error
    }
    
    Code (markup):
    Which you'd just call thus:

    var videoID = getParamFromURL('http://www.youtube.com/watch?v=hGU_ZXnnGP4','v');

    Which would return just the "hGU_ZXnnGP4" part. If you feed in a URL without a hash, or a URL without a v= parameter, it will return -1 giving you error handling, and if there are any other parameters in the URL and v= isn't the first, it will still work -- AND it won't return any extra crap after the video id should there be parameters after.

    Helps to be thorough... as you never know when someone might try to pass it something like:
    var videoID = getParamFromURL('http://www.youtube.com/watch?v=hGU_ZXnnGP4&playnext=1&list=PL939DA943013468D6&feature=results_main','v');

    Which the above code can handle.
     
    Last edited: Dec 24, 2012
    deathshadow, Dec 24, 2012 IP