Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube replace url with video ID using JavaScript and jQuery

i have taken the regex from this http://jsfiddle.net/HfqmE/1/ I have the HTML

<span class="yturl">http://www.youtube.com/watch?feature=endscreen&NR=1&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/watch?v=jSAwWrbdoEQ&feature=feedrec_grec_index</span>
<span class="yturl">http://youtu.be/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/embed/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/v/jSAwWrbdoEQ?version=3&amp;hl=en_US</span>
<span class="yturl">http://www.youtube.com/watch?NR=1&feature=endscreen&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/user/TheGameVEVO#p/a/u/1/jSAwWrbdoEQ</span>

for each span.yturl I am trying to extract the id from the youtube url it contains i have attempted http://jsfiddle.net/HfqmE/40/

$("span.yturl").each(function(){
    var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
    var youtubeurl = $("span.yturl").html();
    var regexyoutubeurl = youtubeurl.match(regex);
    $("span.yturl").html(regexyoutubeurl);
});

this however just leaves the outcome blank please help!!

like image 646
Yusaf Khaliq Avatar asked Aug 04 '26 07:08

Yusaf Khaliq


1 Answers

Match returns an Array. It looks like you want regexyoutubeurl[2].

You are re-querying $("span.yturl") inside your iterator function. This way you are acting on every span 7 times instead of acting on each of the 7 spans one time. Use $(this) instead.

Also, use .text() instead of .html(), lest your & becomes &amp;.

$("span.yturl").each(function(){
    var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
    var youtubeurl = $(this).text();
    var regexyoutubeurl = youtubeurl.match(regex);
    if (regexyoutubeurl) {
        $(this).text(regexyoutubeurl[2]);
    }
});

http://jsfiddle.net/gilly3/HfqmE/53/

like image 168
gilly3 Avatar answered Aug 06 '26 23:08

gilly3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!