Javascript 从 Youtube URL 中提取时间参数

Javascript Extract t Time parameters from Youtube URLs

本文关键字:提取 取时间 参数 URL Youtube Javascript      更新时间:2023-09-26

>我搜索一种提取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

感谢所有;)

您可以使用

此正则表达式来捕获hms值,并将hm作为可选部分:

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

正则表达式演示

正则表达式分解:

'?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