extract and replace (YouTube ONLY) Iframe src

2019-06-13 02:07发布

问题:

If a YouTube iframe html is

<iframe width="560" height="315" src="http://www.youtube.com/embed/VIDEOID" frameborder="0" allowfullscreen></iframe>

The jquery should test the iframe src to see if the first 29 characters match http://www.youtube.com/embed/

if it does apply a jquery to extract the VIDEOID after /embed/ and replace the iframe src with http://www.redirect.mysite.com/?id=VIDEOID

so the iframe's src below

<iframe width="560" height="315" src="http://www.youtube.com/embed/EhrYQrLBiTQ" frameborder="0" allowfullscreen></iframe>

should be replace with

<iframe width="560" height="315" src="http://www.redirect.mysite.com/?id=EhrYQrLBiTQ" frameborder="0" allowfullscreen></iframe>

回答1:

See this fiddle: http://jsfiddle.net/maniator/cRFgv/

Code:

$('iframe').each(function(){
    this.src = this.src.replace('http://www.youtube.com/embed/', 
                                         'http://www.redirect.mysite.com/?id=');
});