# Turning YouTube caption files into clean text and SRT, and the four traps on the way 🧹

> Source: <https://dev.to/timmkal01/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the-way-3fdc>
> Published: 2026-11-26 03:59:09+00:00

**Recommendation:** When ingesting YouTube srv1 captions, loop entity decoding until output is stable (max three passes) and strip tags and whitespace, since a single decode leaves apostrophes as &#39;.
More in the playbook "Fine-tuning and data": <https://wpnews.pro/playbooks/training-data>

*Quotes encoded twice, tags inside lines, two kinds of English, and subtitles that talk over each other.*

Hi! I'm Tim, a self-taught developer in Nairobi. I build small data tools that run as Apify Actors, serverless jobs that people pay for per result.

One of them turns YouTube videos into transcripts. Most people want those for AI tools: a chatbot over a channel, summaries, search. Some want subtitle files. Either way, the job ends with the same small problem: a caption file comes in, and clean text has to come out.

This post skips how you get the file and looks at what's inside it, because that's where the surprises are.

YouTube serves captions in several formats. The simplest is an XML format called `srv1` (tools like yt-dlp can save captions in it too). It looks like this:

```
<?xml version="1.0" encoding="utf-8" ?>
<transcript>
  <text start="0.5" dur="2.1">It&amp;#39;s &amp;quot;fine&amp;quot; &amp;amp; good</text>
  <text start="2.6" dur="1.9">line
break <font color="#E5E5E5">here</font></text>
  <text start="4.5" dur="1">   </text>
  <text start="5.5" dur="2">caf&#233; &#x2019;ok&#x2019;</text>
</transcript>
```

One `<text>` per caption line, with a start time and a duration in seconds. Simple enough to parse with one regex. That small example holds three of the four traps.

Look at the first line again: `It&#39;s`. That's an apostrophe encoded as `'`, and then the `&` of that encoded again as `&`.

Decode it once, the way any XML parser would, and you get:

```
It&#39;s &quot;fine&quot; &amp; good
```

A parser that decodes once saves exactly that. It looks fine in a quick test, because most lines have no quotes, and then every "it's" and "don't" in a long transcript comes out as `'`.

The fix is to decode until the text stops changing:

``` js
const NAMED = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };

function decodeOnce(s) {
    return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
        if (e[0] === '#') {
            const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
            return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : m;
        }
        return NAMED[e.toLowerCase()] ?? m;
    });
}

// Caption text is often encoded twice (&amp;#39;), so decode until it stops changing, at most 3 times.
export function decodeEntities(s) {
    let out = String(s ?? '');
    for (let i = 0; i < 3; i++) {
        const next = decodeOnce(out);
        if (next === out) break;
        out = next;
    }
    return out;
}
```

A few details that matter:

`é` is decimal and `’` is hex. Both have to work, and `String.fromCodePoint` handles characters outside the basic range, which `fromCharCode` gets wrong.`&foo;` isn't a real entity, so it's left alone instead of becoming an empty string.`&amp;lt;` takes three passes to become `<`. Three is enough for what YouTube sends, and the cap stops a strange input from looping on.
There's a trade-off: if a caption genuinely contained the text `<`, it would be decoded too far. In speech captions that almost never happens, so I accepted it.

The second line has a line break in the middle and a `<font>` tag around one word. Caption text can carry styling like that, and none of it belongs in a transcript.

The whole line parser:

``` js
export function parseSrv1(xml) {
    const segments = [];
    const re = /<text\b([^>]*)>([\s\S]*?)<\/text>|<text\b([^>]*)\/>/g;
    let m;
    while ((m = re.exec(String(xml ?? '')))) {
        const attrs = m[1] ?? m[3] ?? '';
        const start = Number((attrs.match(/\bstart="([\d.]+)"/) || [])[1]);
        const duration = Number((attrs.match(/\bdur="([\d.]+)"/) || [])[1] ?? 0);
        const text = decodeEntities(m[2] ?? '')
            .replace(/<[^>]+>/g, '')   // drop styling tags
            .replace(/\s+/g, ' ')      // line breaks and runs of spaces become one space
            .trim();
        if (!Number.isFinite(start) || !text) continue;   // skip blank lines and broken ones
        segments.push({ start: round(start), duration: round(Number.isFinite(duration) ? duration : 0), text });
    }
    return segments;
}

const round = (n) => Math.round(n * 1000) / 1000;
```

Three things happen to every line:

`<font color="#E5E5E5">here</font>` becomes `here`.` line\nbreak` becomes `line break`.`<text>` in the example is only spaces. Keeping it would put an empty cue in the subtitle file.
The regex also accepts a self-closing `<text ... />`, which is an empty line written the short way.

**Order matters here.** Tags are stripped after decoding. That means an encoded `<` followed later by `>` in the same line would be decoded into something that looks like a tag and then removed. Captions of speech practically never contain that. If yours might, strip tags first and decode second.

From the example, the parser returns:

```
[
  { start: 0.5, duration: 2.1, text: 'It\'s "fine" & good' },
  { start: 2.6, duration: 1.9, text: 'line break here' },
  { start: 5.5, duration: 2,   text: 'café ’ok’' },
]
```

For AI tools I join those into one block of text. A 15-minute speech comes out at about 2,300 words, small enough to hand to a model whole. The segments stay in the output too, because timestamps are what let you link an answer back to the second it was said.

A video usually has several caption tracks. Each has a language code, and YouTube marks the ones its speech recognition made: `kind` is `"asr"`, or the track's `vssId` starts with `a.`.

So "give me English" isn't one question, it's three:

`en` match `en-GB`?
My rules:

``` js
export const isAuto = (track) => track?.kind === 'asr' || /^a\./.test(track?.vssId ?? '');
export const baseLanguage = (code) => String(code ?? '').toLowerCase().split(/[-_]/)[0];

export function pickTrack(tracks, { languages = ['en'], preferManual = true, fallbackToAny = true } = {}) {
    const list = (tracks ?? []).filter((t) => t?.baseUrl);
    if (!list.length) return null;
    for (const lang of languages) {
        const exact = (t) => String(t.languageCode ?? '').toLowerCase() === lang;
        const loose = (t) => baseLanguage(t.languageCode) === baseLanguage(lang);
        const candidates = [...list.filter(exact), ...list.filter((t) => !exact(t) && loose(t))];
        if (!candidates.length) continue;
        const manual = candidates.find((t) => !isAuto(t));
        const auto = candidates.find((t) => isAuto(t));
        return { track: preferManual ? (manual ?? auto) : (auto ?? manual), matched: true };
    }
    if (!fallbackToAny) return null;
    // Nothing matched: the automatic track is in the language actually spoken, so it's the best guess.
    return { track: list.find(isAuto) ?? list[0], matched: false };
}
```

My favourite test case: a video has Arabic, automatic English, British English written by a person, and Spanish. Asked for `en`, which wins?

``` js
// T(code, auto) builds a fake track for the test
const tracks = [T('ar'), T('en', true), T('en-GB'), T('es')];
pickTrack(tracks, { languages: ['en'] }).track.languageCode;   // 'en-GB'
```

The written `en-GB` beats the automatic `en`, even though `en` is the exact match. A person's captions have punctuation and fewer misheard words, and for a transcript that matters more than the region. If someone wants the automatic one, `preferManual: false` flips it.

When nothing matches, I return `matched: false` and say so in the output. Quietly handing back Arabic to someone who asked for English would look like a bug.

An SRT file is the easy part, except for one thing. Each cue needs an end time, and `start + duration` doesn't always stop before the next line starts. When cues overlap, players show two lines stacked on top of each other.

So each end is clamped to the next start:

``` js
function srtTime(seconds) {
    const ms = Math.max(0, Math.round(seconds * 1000));
    const h = Math.floor(ms / 3_600_000);
    const m = Math.floor((ms % 3_600_000) / 60_000);
    const s = Math.floor((ms % 60_000) / 1000);
    const pad = (n, w = 2) => String(n).padStart(w, '0');
    return `${pad(h)}:${pad(m)}:${pad(s)},${pad(ms % 1000, 3)}`;
}

export function toSrt(segments) {
    return segments.map((s, i) => {
        const next = segments[i + 1];
        let end = s.start + (s.duration || 2);       // no duration: show it for 2 seconds
        if (next && end > next.start) end = next.start;
        return `${i + 1}\n${srtTime(s.start)} --> ${srtTime(end)}\n${s.text}\n`;
    }).join('\n');
}
```

Three cues, the first one too long, the second with no duration, the third an hour in:

``` php
1
00:00:00,500 --> 00:00:03,000
a

2
00:00:03,000 --> 00:00:05,000
b

3
01:01:01,250 --> 01:01:02,750
c
```

The first cue wanted to run until 5.5 seconds and was cut at 3.0, where the second starts. The second had no duration, so it got 2 seconds. And SRT wants a **comma** before the milliseconds, not a dot. A dot is WebVTT's style, and some players and editors won't read an SRT file that uses one.

All of these are pure functions with no network calls, so each one has a small unit test, the British English case included. Tests like that are cheap to write and they pin down the decisions, not just the parsing.
