Parse, Validate and Convert SRT and WebVTT in JavaScript
A small tested JavaScript module that parses SRT, validates cues, converts SRT to WebVTT and back, and shifts timings, with the traps that break naive code.
Try it now: AI Subtitle Generator — timed subtitles from speech in 20 languages, processed in your browser.
Most SRT "parsers" on the web are a regular expression and a hope. This module is small, handles the traps that break the usual snippets, and was run against the tests below in Node.js v24.
The traps
| Trap | Why it bites |
|---|---|
Byte-order mark () at the start | The first block's counter fails to parse |
Windows line endings (\r\n) | Splitting on \n\n misses blank lines |
| Comma vs full stop in timestamps | SRT uses ,; WebVTT uses . |
| Missing counters | Some files omit the numbers |
| End not after start | WebVTT requires end > start; players misbehave |
| Extra blank lines | Inflates the block count |
The code
// srt.mjs
const TIME = String.raw`(\d{2}):(\d{2}):(\d{2})[,.](\d{3})`;
const RANGE = new RegExp(String.raw`^${TIME}\s*-->\s*${TIME}`);
const toMs = (h, m, s, f) => ((+h * 60 + +m) * 60 + +s) * 1000 + +f;
export function parseSrt(text) {
const blocks = text
.replace(/^/, "") // strip a byte-order mark
.replace(/\r\n?/g, "\n") // normalise line endings
.trim()
.split(/\n{2,}/);
return blocks.map((block, n) => {
const lines = block.split("\n");
const hasIndex = /^\d+$/.test(lines[0].trim());
const m = RANGE.exec((lines[hasIndex ? 1 : 0] ?? "").trim());
if (!m) throw new Error(`Block ${n + 1}: no valid time range`);
const start = toMs(...m.slice(1, 5));
const end = toMs(...m.slice(5, 9));
if (end <= start) throw new Error(`Block ${n + 1}: end is not after start`);
return { start, end, text: lines.slice(hasIndex ? 2 : 1).join("\n") };
});
}
const pad = (n, w) => String(n).padStart(w, "0");
function stamp(ms, sep) {
const h = Math.floor(ms / 3600000), m = Math.floor(ms / 60000) % 60, s = Math.floor(ms / 1000) % 60;
return `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)}${sep}${pad(ms % 1000, 3)}`;
}
export const toVtt = (cues) =>
`WEBVTT\n\n${cues.map((c) => `${stamp(c.start, ".")} --> ${stamp(c.end, ".")}\n${c.text}`).join("\n\n")}\n`;
export const toSrt = (cues) =>
cues.map((c, i) => `${i + 1}\n${stamp(c.start, ",")} --> ${stamp(c.end, ",")}\n${c.text}`).join("\n\n") + "\n";
export const shift = (cues, ms) =>
cues.map((c) => ({ ...c, start: Math.max(0, c.start + ms), end: Math.max(0, c.end + ms) }));The tests (they pass)
import assert from "node:assert/strict";
import { parseSrt, toVtt, toSrt, shift } from "./srt.mjs";
const srt = "1\r\n00:00:01,200 --> 00:00:03,800\r\nWelcome back.\r\n\r\n" +
"2\r\n00:00:04,000 --> 00:01:06,500\r\nLine one\r\nline two\r\n";
const cues = parseSrt(srt);
assert.deepEqual(cues[0], { start: 1200, end: 3800, text: "Welcome back." });
assert.equal(cues[1].end, 66500);
assert.equal(cues[1].text, "Line one\nline two");
assert.ok(toVtt(cues).startsWith("WEBVTT\n\n00:00:01.200 --> 00:00:03.800\nWelcome back."));
assert.throws(() => parseSrt("1\n00:00:05,000 --> 00:00:04,000\nx"), /end is not after start/);
assert.throws(() => parseSrt("1\nnot a time\nx"), /no valid time range/);
assert.equal(shift(cues, -2000)[0].start, 0); // clamps at zeroUsing it
const vtt = toVtt(parseSrt(srtText)); // SRT → WebVTT const srt2 = toSrt(parseSrt(srtText)); // normalise/renumber an SRT const later = toSrt(shift(parseSrt(srtText), 1500)); // delay by 1.5 s
For WebVTT as input, the same range regex accepts the full stop, but real WebVTT also allows optional hours (mm:ss.ttt), cue settings after the times, NOTE and STYLE blocks and a WEBVTT header. This parser does not handle those; use a dedicated WebVTT library when you need the full format, or see the SRT vs VTT comparison for what differs.
Debugging helpers
- A regex tester helps adapt the range pattern (for example to accept
mm:sstimestamps). - A diff checker shows exactly what a conversion changed.
What is not covered
Styling tags, positioning, multi-language tracks and encoding detection (read files as UTF-8). Where do SRTs come from? The subtitle generator exports Subtitles (.srt) and Web subtitles (.vtt) after a free Google sign-in.
Last updated