Parse Multiline Language Blocks with JavaScript

When each translated block ends with a marker such as [en], parse the whole input with one global regular expression. Capture the text and language separately instead of splitting on newlines, because the text itself may contain any number of lines.

Last updated: October 19, 2026.

const input = `First line
Second line [en]
Première ligne
Deuxième ligne [fr]`;

const pattern = /(?<text>[\s\S]*?)\[(?<language>[A-Za-z]{2})\](?:\r?\n|$)/g;

const blocks = Array.from(input.matchAll(pattern), ({ groups }) => ({
  language: groups.language.toLowerCase(),
  text: groups.text.trim(),
}));

console.log(blocks);

The first named group stops at the next valid marker. [\s\S] matches line breaks as well as ordinary characters, while the final group accepts a two-letter language code and normalizes it to lowercase.

Why matchAll works better than split

MDN documents that matchAll() returns every global match together with its capture groups. That makes each result a complete record rather than alternating pieces from split(). The regular expression must include the g flag.

The non-greedy *? is important. A greedy repetition would consume through later markers and could collapse several translations into one result. The two-letter rule is deliberately narrow; change it to a tested list such as en|fr|de if only specific languages are allowed.

Handle newlines and invalid input deliberately

The regular-expression s flag also makes a dot match line terminators, so .*? with gs is an equivalent modern form. [\s\S] is useful when the same pattern must work in older JavaScript runtimes.

After parsing, compare the end of the final match with the input length. Any remaining non-whitespace text indicates a missing or malformed marker and should produce a validation message rather than being discarded. Normalize line endings only after parsing if exact source positions matter.

Continue with JavaScript array processing, downloading generated text, and inspecting Unicode code points.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov