Javascript 从 Youtube URL 中提取 t 时间参数

标签 javascript regex youtube

我搜索了一种提取t时间参数内容的方法

所以,例如:

https://youtu.be/YykjpeuMNEk?t=2m3s
https://youtu.be/YykjpeuMNEk?t=3s
https://youtu.be/YykjpeuMNEk?t=1h2m3s

我想获取 h、m 和 s 值。

我可以想象我必须使用 RegEx 才能完成工作,但我找不到正确的表达式字符串(在这一点上是新手)

我暂时只有这个:

var matches = t.match(/[0-9]+/g);

我使用这个工具来测试不同的表达式,但无法正确格式化它并确保内容与 h、m 和 s 完全相关。

如果你有任何想法;)

适合我的答案:

url = 'https://youtu.be/vTs7KXqZRmA?t=2m18s';
var matches = url.match(/\?t=(?:(\d+)h)?(?:(\d+)m)?(\d+)s/i);
var s = 0;
s += matches[1] == undefined ? 0 : (Number(matches[1])*60*60);
s += matches[2] == undefined ? 0 : (Number(matches[2])*60);
s += matches[3] == undefined ? 0 : (Number(matches[3]));
console.log(s);

输出:

138

感谢大家;)

最佳答案

您可以使用此正则表达式通过 h 捕获 hms 值m 作为可选部分:

/\?t=(?:(\d+)h)?(?:(\d+)m)?(\d+)s/i

RegEx Demo

正则表达式分解:

\?t=        # match literal text ?t=
(?:         # start capturing group
   (\d+)h   # match a number followed by h and capture it as group #1
)?          # end optional capturing group
(?:         # start capturing group
   (\d+)m   # match a number followed by m and capture it as group #2
)?          # end optional capturing group
(\d+)s      # # match a number followed by s and capture it as group #3

关于Javascript 从 Youtube URL 中提取 t 时间参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803261/

相关文章:

java - 为什么没有 glob :* match any path in PathMatcher?

regex - 巴基斯坦手机号码的正则表达式

html - 从 Perl 中的 HTMl/XML 标签中提取文本

javascript - youtube视频播放完后如何自动退出浏览器

iphone - MPMoviePlayerController 播放 YouTube 视频

youtube - 我如何要求用户为他们的youtube视频提供我的链接

javascript - jQuery 循环插件 For Loop

javascript - 将鼠标事件传递给 HTML 中下面的元素

javascript - 关于修改 Node 原型(prototype)的担忧

javascript - JSON - 输入第二级对象