我搜索了一种提取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
和 捕获
作为可选部分:h
、m
和 s
值m
/\?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
关于Javascript 从 Youtube URL 中提取 t 时间参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803261/