Timecode parsing for user input
I have a script that allows users to enter timecode as a string, and I wanted it to perform the same as the Timecode inputs in the rest of the program: if they type "1..." I want it to register as 1:00:00:00 without them having to type a correctly formatted string.
This. Took. Ages. I descended deep into the regex underworld, but I'm happy to say that I managed to placate the JS gods with my mad skillz on the lyre and returned victorious. So for any other young traveller preparing to take the journey, here's what I worked out. If you have suggestions, please, let me know.
function parseTimeString(theString, comp) {
comp = app.project.activeItem; //need an active comp in order to get the frameDuration
if (comp) {
theString = "" + theString;
//allows user to lazily enter timecode, eg. to enter 1 minute you type 1.. rather than 0:1:0:0
//this took ages to work out..
var hrsStr = theString.match(/(\d+)\D\d*\D\d*\D\d*$/); //matches "0:1:2:3" and "0..." and returns '0'
var minStr = theString.match(/(\d+)\D\d*\D\d*$/); //matches "0:1:2:3" , "1,2.3" and "1.." and returns 1
var secStr = theString.match(/(\d+)\D\d*$/); //and so on..
var frmStr = theString.match(/(\d+)$/);
//convert the strings to time values
var hrs = hrsStr
? parseInt(hrsStr)
: 0;
var min = minStr
? parseInt(minStr)
: 0;
var sec = secStr
? parseInt(secStr)
: 0;
var frm = frmStr
? parseInt(frmStr)
: 0;
//return the result as time, measured in seconds
return 3600 * hrs + 60 * min + sec + comp.frameDuration * frm;
}
return false;
}
