I am trying to make a bookmarklet to get video id of current youtube url and go to a website with the video id in the query string. location.href
helps me to get current url.
javascript:location.href='http://www.sampledomaincom/mybookmarkutility.html?v='+encodeURIComponent(location.href);
How to get video ID directly from url and append it to this query string as +'&videoid='+
You want a bookmarklet to: get video ID directly from url and append it to this query string as +'&videoid='+
.
window.location.search
gives us the search-part. We strip of the leading ?
, split it by &
and finally split every resulting value by =
. If now there is an identifier v
then we continue (using it's value), otherwise we alert an error..
Now let's apply this, re-factor the code and put it in an IIF (to overcome a lot of problems):
// alert edition:
javascript:(function(L,t,i){for(i=(t=L.search.slice(1).split('&')).length;i--&&(t[i]=t[i].split('='))[0]!=='v';);~i&&(t=t[i][1])?alert('http://www.sampledomain.com/mybookmarkutility.html?v='+encodeURIComponent(L.href)+'&videoid='+t):alert('No videoID found.')})(window.location);
// working edition:
javascript:(function(L,t,i){for(i=(t=L.search.slice(1).split('&')).length;i--&&(t[i]=t[i].split('='))[0]!=='v';);~i&&(t=t[i][1])?L.href='http://www.sampledomain.com/mybookmarkutility.html?v='+encodeURIComponent(L.href)+'&videoid='+t:alert('No videoID found.')})(window.location);
And an updated regex-version (it's a bit shorter):
// alert edition:
javascript:(function(L,t){(t=/[?&]v=([^&]+)/.exec(L.search))?alert('http://www.sampledomain.com/mybookmarkutility.html?v='+encodeURIComponent(L.href)+'&videoid='+t[1]):alert('No videoID found.')})(window.location);
// working edition:
javascript:(function(L,t){(t=/[?&]v=([^&]+)/.exec(L.search))?L.href='http://www.sampledomain.com/mybookmarkutility.html?v='+encodeURIComponent(L.href)+'&videoid='+t[1]:alert('No videoID found.')})(window.location);
Hope this helps!