-
Notifications
You must be signed in to change notification settings - Fork 53
/
subtitle_util.js
53 lines (50 loc) · 1.78 KB
/
subtitle_util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Created by qiaoxueshi on 6/27/15.
*/
module.exports = {
webvttLinesToSrtLines: function(webvttLines) {
//match time line, such as: 00:00:29.586 --> 00:00:30.106 A:middle
var timeLineRegex = /^([0-9:.]+)\.(\d+ --> [0-9:.]+)\.(\d+)/;
var statements = [];
var statement = {};
webvttLines.forEach(function(line) {
if (line.trim().length != 0) {
var groups = line.match(timeLineRegex);
if (groups) {
if (statement.timeLine) {
statements.push(statement);
statement = {};
}
statement.timeLine = groups[1] + "," + groups[2] + "," + groups[3];
} else {
line = line.replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&");
if (statement.subtitles) {
statement.subtitles.push(line);
} else {
statement.subtitles = [line];
}
}
}
});
if (statement.timeLine) {
statements.push(statement);
}
statements = statements.filter(function (line, index, lines) {
if (index > 0 && line.timeLine === lines[index - 1].timeLine) {
return false;
} else {
return true;
}
});
var finalLines = [];
statements.forEach(function (srtLine, index) {
finalLines.push(index + 1);
finalLines.push(srtLine.timeLine);
srtLine.subtitles.forEach(function (subtitle) {
finalLines.push(subtitle)
});
finalLines.push("\n");
});
return finalLines;
}
};