我想要得到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


当前回答

我对mantish的正则表达式做了一些轻微的更改,以包括来自J W和矩阵的答案的所有测试用例;因为一开始并不是对所有人都有效。可能还需要进一步的修改,但据我所知,这至少涵盖了大部分链接:

- (?): [&] vi ? = |嵌入- | \ / \ d d ? \ | - vi ? \ / | https: / \ / (?: www。)? youtu \。be /) ([^ & \ n ? # +) -

var url = ''; // get it from somewhere

var youtubeRegExp = /(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/;
var match = url.match( youtubeRegExp );

if( match && match[ 1 ].length == 11 ) {
    url = match[ 1 ];
} else {
    // error
}

进一步测试:

http://regexr.com/3fp84

其他回答

我对mantish的正则表达式做了一些轻微的更改,以包括来自J W和矩阵的答案的所有测试用例;因为一开始并不是对所有人都有效。可能还需要进一步的修改,但据我所知,这至少涵盖了大部分链接:

- (?): [&] vi ? = |嵌入- | \ / \ d d ? \ | - vi ? \ / | https: / \ / (?: www。)? youtu \。be /) ([^ & \ n ? # +) -

var url = ''; // get it from somewhere

var youtubeRegExp = /(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/;
var match = url.match( youtubeRegExp );

if( match && match[ 1 ].length == 11 ) {
    url = match[ 1 ];
} else {
    // error
}

进一步测试:

http://regexr.com/3fp84

我对“jeffreypriebe”提供的Regex做了一个增强,因为他需要一种YouTube URL是视频的URL,当他们通过一个频道看。

不,但这是我武装的函数。

<script type="text/javascript">
function youtube_parser(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    var match = url.match(regExp);
    return (match&&match[7].length==11)? match[7] : false;
}
</script>

这些是支持的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&amp;hl=en_US&amp;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

可在[http://web.archive.org/web/20160926134334/]找到 http://lasnv.net/foro/839/Javascript_parsear_URL_de_YouTube

我把Lasnv的回答简化了一点。

它还修复了WebDeb描述的错误。

下面就是:

var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
  return match[2];
} else {
  //error
}

下面是一个regexer链接: http://regexr.com/3dnqv

videoId = videoUrl.split('v=')[1].substring(0,11);

如果有人需要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
}