Skip to content

Instantly share code, notes, and snippets.

@Subilan
Created June 20, 2021 16:39
Show Gist options
  • Save Subilan/37dab4e02d56cb1c8fd6fe05f593a4f7 to your computer and use it in GitHub Desktop.
Save Subilan/37dab4e02d56cb1c8fd6fe05f593a4f7 to your computer and use it in GitHub Desktop.
change srt subtitle data to json using javascript
// change minute time with milisecond to seconds
// e.g. 02:04:33,229
function toSeconds(input) {
let a = input.split(',');
let x = a[0].split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0);
let y = a[1] / 1000
return x + y;
}
function SrtToJson(srt) {
let arr = srt.split('\n');
arr = arr.filter(x => x.length > 0);
arr = arr.filter(x => isNaN(x));
let m = 0;
let n = [];
let next = false;
arr.forEach(x => {
if (!n[m]) n[m] = [];
if (x.includes(' --> ')) {
let z = x.split(' --> ');
n[m][1] = toSeconds(z[0]);
n[m][2] = toSeconds(z[1]);
} else {
n[m][0] = x;
next = true;
}
if (next) {
m++;
next = false;
}
});
return JSON.stringify(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment