Skip to content

Instantly share code, notes, and snippets.

@korny
Created July 3, 2014 13:00
Show Gist options
  • Save korny/c31e1017b2e23c2f4042 to your computer and use it in GitHub Desktop.
Save korny/c31e1017b2e23c2f4042 to your computer and use it in GitHub Desktop.
Simple SRT parser in JavaScript
function srtTimeToSeconds(time) {
var match = time.match(/(\d\d):(\d\d):(\d\d),(\d\d\d)/);
var hours = +match[1],
minutes = +match[2],
seconds = +match[3],
milliseconds = +match[4];
return (hours * 60 * 60) + (minutes * 60) + (seconds) + (milliseconds / 1000);
}
function parseSrtLine(line) {
var match = line.match(/(\d\d:\d\d:\d\d,\d\d\d) --> (\d\d:\d\d:\d\d,\d\d\d)\n(.*)/m);
return {
start: srtTimeToSeconds(match[1]),
end: srtTimeToSeconds(match[2]),
text: match[3].trim()
};
}
function parseSrt(srt) {
var lines = srt.split(/(?:^|\n\n)\d+\n|\n+$/g).slice(1, -2);
return $.map(lines, parseSrtLine);
}
@Arecsu
Copy link

Arecsu commented Jan 12, 2023

This is beautiful. Simple to use and read. I think I'm going to use this in a future project :)

@korny
Copy link
Author

korny commented Jan 19, 2023

Thanks! I don’t even remember why I wrote it 🤔

@screening4ashes
Copy link

Is this using jQuery? I get an error on the line with $.map, I'm using plain vanilla JS....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment