你好,我在这里找到了很多线程,解释了如何从 url 中解析 youtube id,但我没有找到任何可以从字符串中提取 youtube 视频 id 的线程。
我需要一个可以从 url 返回 YouTube 视频 ID 的函数
例如我有字符串
> Hello this is my string and this is my youtube video : http://youtube.com/w=abcdef and this is my blog http://stackoverflow.com etc etc.
它应该返回
> Hello this is my string and this is my youtube video : abcdef and this is my blog http://stackoverflow.com etc etc.
Trying this function but not working properly
function linkifyYouTubeURLs(text) {
var re = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
return text.replace(re,
'<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');
}
最佳答案
试试这个:
var re = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
<强> REGEX DEMO
关于javascript - 使用javascript从字符串中解析youtube视频id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788349/