Convert hours, minutes to seconds by parsing youtube t = queryparam in javascript / JQuery
I want to parse the t = timestamp in the youtube url (" http://youtu.be/O4tzHn-EuHc?t=1h5m16s ") and calculate the total number of seconds I need to pass as the initial parameter to embed the url youtube http://www.youtube.com/embed/XGSy3_Czz8k?start= "
To get the hours, minutes and seconds I am using reg-exp as shown below. Let me know that any improvement can be made in the code to keep it simple.
var url ="http://youtu.be/XGSy3_Czz8k?t=1h5m16s";
var timeStamp = url.match("t=(.)*?[&|(\s)]");
var hours = timeStamp[0].match(/(\d)+h/);
var minutes = timeStamp[0].match(/(\d)+m/);
var seconds = timeStamp[0].match(/(\d)+s/);
var totalTimeInSeconds = 0;
if (hours) {
hours = hours[0].replace("h","");
totalTimeInSeconds += hours * 60 * 60;
}
if (minutes) {
minutes = minutes[0].replace("m","");
totalTimeInSeconds += minutes * 60;
}
if (seconds) {
seconds = seconds[0].replace("s","")
totalTimeInSeconds += seconds * 1;
}
console.log("hours:"+hours);
console.log("minutes:"+minutes);
console.log("seconds:"+seconds);
console.log("TotalTimeInSeconds:"+ totalTimeInSeconds);
<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k?start="+totalTimeInSeconds>
</iframe>
source to share
I think a good source for comments for your code would be codereview .
You can get rid of your String.replace calls by slightly adjusting your regexes like this:
var hours = timeStamp[0].match(/(\d+)h/);
var minutes = timeStamp[0].match(/(\d+)m/);
var seconds = timeStamp[0].match(/(\d+)s/);
With these regular expressions, you will grab all the digits at once and you can use them like this:
if (hours) {
totalTimeInSeconds += parseInt(hours[1], 10) * 60 * 60;
}
if (minutes) {
totalTimeInSeconds += minutes[1] * 60;
}
if (seconds) {
totalTimeInSeconds += seconds[1];
}
Usage parseInt
is not required here, but I would most likely introduce it to make it more explicit that the conversion is taking place. I also suggest timeStamp
setting up a regex for your variable so that it already narrows down to the parameter t
more.
source to share
try it
var url ="http://youtu.be/XGSy3_Czz8k?t=1h5m16s";
var timeStamp = url.match("t=(.)*?[&|(\s)]");
timeStampSplitted = timeStamp[0].replace("t=","").replace("h", ":").replace("m", ":").replace("s", "").split(':');
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+timeStampSplitted[0]) * 60 * 60 + (+timeStampSplitted[1]) * 60 + (+timeStampSplitted[2]);
source to share
I think the simplest is to use a function RegExp
replace
:
var seconds = "1h5m16s".replace(/([0-9]+)h([0-9]+)m([0-9]+)s/, function(match, p1, p2 ,p3) {
return p1 * 60 * 60 + p2 * 60 + p3 * 1
})
Note p3 * 1
is a shortcut for parseInt
. Also note that this replace
will return you a string - remember to convert to a number if necessary.
source to share