Created
July 3, 2014 13:00
-
-
Save korny/c31e1017b2e23c2f4042 to your computer and use it in GitHub Desktop.
Simple SRT parser in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Thanks! I don’t even remember why I wrote it 🤔
Is this using jQuery? I get an error on the line with $.map, I'm using plain vanilla JS....
im not sure if this has any bugs but i modified it to account for srt files that use \r\n\r\n as well as new lines in text
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([\S\s]*)/m);
return {
start: srtTimeToSeconds(match[1]),
end: srtTimeToSeconds(match[2]),
text: match[3].trim()
};
}
function parseSrt(srt) {
var lines = srt.replaceAll('\r', '').split(/(?:^|\n\n)\d+\n|\n+$/g).slice(1, -2);
return $.map(lines, parseSrtLine);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is beautiful. Simple to use and read. I think I'm going to use this in a future project :)