2015-12-27 87 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(); 
}