我想要得到v=id从YouTube的URL与JavaScript(没有jQuery,纯JavaScript)。

YouTube URL格式示例

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

http://www.youtube.com/watch?v=u8nQa1cJyX8

或在URL中包含视频ID的任何其他YouTube格式。

这些格式的结果

u8nQa1cJyX8


当前回答

如果有人需要Kotlin中的完美函数来节省他们的时间。希望这能有所帮助

fun extractYTId(ytUrl: String?): String? {
    var vId: String? = null
    val pattern = Pattern.compile(
        "^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$",
        Pattern.CASE_INSENSITIVE
    )
    val matcher = pattern.matcher(ytUrl)
    if (matcher.matches()) {
        vId = matcher.group(1)
    }
    return vId
}

其他回答

我喜欢Surya的回答。只是一个行不通的案例……

String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

并不适用于

youtu.be/i4fjHzCXg6c  and  www.youtu.be/i4fjHzCXg6c

升级版:

String regExp = "/?.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

适用于所有人。

我有一个正则表达式,支持常用的url,其中还包括YouTube短片

正则表达式模式:

(youtu *。*)\ /(看\ ? v = |嵌入\ / | |短裤 |)(.*?((?=[&#?])|$))

Javascript返回方法:

function getId(url) {
  let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
  return regex.exec(url)[3];
}

支持的URL类型:

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI

与测试:

https://regex101.com/r/5JhmpW/1

这个短片适用于我尝试过的每个youtube链接。

url.match(/([a-z0-9_-]{11})/gim)[0]

https://regexr.com/3nsop

我们认识这些人物?”v="永远不会出现多于一个,但'v'可以以某种方式出现在本我本身,所以我们使用"?V ="作为分隔符。看到它在这里工作

//Get YouTube video Id From Its Url

     $('button').bind('click',function(){
var 
url='http://www.youtube.com/watch?v=u8nQa1cJyX8',
videoId = url.split('?v='),//Split data to two
YouTubeVideoId=videoId[1];
alert(YouTubeVideoId);return false;

});

<button>Click ToGet VideoId</button>

一个:

var id = url.match(/(^|=|\/)([0-9A-Za-z_-]{11})(\/|&|$|\?|#)/)[2]

它适用于此线程中显示的任何URL。

它不会工作时,YouTube添加一些其他参数与11个base64字符。在那之前,这是最简单的方法。