2015-12-27 91 views
-3

我正在制作一个小型的YouTube应用程序,但有一个问题。我收到2种YouTube网址,但都无法嵌入。所以我必须改变它们。现在我的逻辑是从URL中提取YouTube视频代码。是2个链接我得到如下:我如何更改YouTube网址

https://youtu.be/TbvMgLDVUd4 - >我需要的TbvMgLDVUd4

https://www.youtube.com/watch?v=72yuprTXvMI->我需要的72yuprTXvMI

所以我的想法是这样的,但我不知道我们究竟如何这...

if (videos.results[i].titlemay_link === https://www.youtube.com/watch?v=.........) { 
     var output = only get the .......... 
     } else { 
     var output = only get the .......... 
     } 

     content += '<iframe width="560" height="315" src="' + outcome + '" frameborder="0" allowfullscreen></iframe>'; 
+1

的[获取破折号后一切以JavaScript字符串(可能的复制http://stackoverflow.com/questions/573145/get-everything-after-the-dash-in-a-string- in-javascript) – TRose

+0

RegEx是你的朋友,如果链接可以变得更复杂,否则你可以用一个简单的替换来解决这个问题。 – Shomz

回答

1

检查该字符串是否包含?v=,如果是,则在此之后获取内容。如果没有,请在/的最后一次出现后获取内容。

var token; 
if(url.indexOf("?v=") > -1){ 
    // Create an array using "?v=" as a delimiter, and we want the content on the right side of the original string 
    token = url.split("?v=")[1]; 
}else{ 
    // Create an array using "/" as a delimiter, and pop() to get the last element in the array 
    token = url.split("/").pop(); 
}