2016-03-04 15 views
1

我搜索的方式来提取t时刻的参数内容的Javascript提取t时间参数

因此,举例来说:

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

我想获得的H,M和S值。

我能像我在为了使工作中使用正则表达式,但我无法找到合适的表达字符串(在这一点上有点新手)

我只有这个的时刻:

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 

感谢所有;)

+0

https://regex101.com/r/rR3eH9/1 –

+0

由于@WiktorStribiżew,就像一个魅力! – Polykrom

+1

我猜anubhava的作品呢?如果没有,我会发布我的答案。 –

回答

2

你可以使用这个正则表达式来捕获hms值与hm作为任选部件:

/\?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 
+1

Woow ...很好..完美的作品! thansk很多@anubhava :) – Polykrom