Javascript Extract t Time parameters from Youtube URLs

时间:2016-03-04 18:17:47

标签: javascript regex youtube

I search a way to extract the t time parameters content

So , for example :

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

I'd like to get the h,m and s values.

I can image i have to use RegEx in order to make the work, but i'm cannot find the right expression string (little novice in that point)

I just have this for the moment :

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

i use this tool to test different expressions, but unable to format it correctly and be sure that the content is exactly related to h,m and s.

If you have any idea ;)

ANSWER THAT WORKS FOR ME :

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);

output :

138

thanks to all ;)

1 个答案:

答案 0 :(得分:2)

You can use this regex to captre h, m and s values with h and m as optional parts:

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

RegEx Demo

RegEx Breakup:

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