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);
}
@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....

@salut1618
Copy link

salut1618 commented Jun 8, 2024

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