Emmanuel Akinfulubi

JavaScriptString

Decode a run-length encoded string in JavaScript

Advanced · 4 min read

Compressing text is only half the job. To get the original back, you need a decoder. In run-length encoding, '3a2bc' means "three as, two bs, one c", so decoding it gives 'aaabbc'. Every compression format has this pair: an encoder that shrinks and a decoder that restores.

In this tutorial you will write decode in one line with replace and repeat. You will see the one-character mistake that breaks every count over nine, and check what the decoder does with input that isn't valid. You should know replace with a regex and Number(). Capture groups and replace callbacks are explained below.

Reading the encoded text

Each piece of the encoded string is either:

  • a count followed by a character, like 3a or 12a, or
  • a character on its own, like c, which means a run of one.

A count is a run of digits. The character it applies to is the next thing that is not a digit.

Capture groups and a replace callback

In a regex, brackets ( ) capture what they match so you can use it. ([0-9]+)([^0-9]) has two groups: one or more digits, then one character that isn't a digit.

When you pass a function to replace, it is called for every match. Its first argument is the whole match, and the next arguments are the captured groups. Whatever it returns replaces the match.

'a'.repeat(3) gives 'aaa': it repeats a string a number of times.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

58 Run-length decode

hard

Expand '3a2bc' back to 'aaabbc'. Make sure a two-digit count is read as one number, and check what happens to a malformed input.

Stuck? Three hints, smallest first
  1. 1. A count is a run of digits followed by the character it applies to.
  2. 2. Reading only one digit breaks the moment a count reaches ten.
  3. 3. repeat does the expansion once you have the count as a number.

Step 1: match one piece

Step 1

const [whole, count, c] = '3a'.match(/([0-9]+)([^0-9])/);
console.log(whole, count, c); // 3a 3 a
console.log(c.repeat(Number(count))); // 'aaa'

match without the g flag returns the whole match followed by the groups, and destructuring names them. count is the text '3', so Number() turns it into the number 3 before repeat uses it.

Step 2: decode the whole string

Step 2

const decode = (encoded) =>
  encoded.replace(/([0-9]+)([^0-9])/g, (_, count, c) => c.repeat(Number(count)));
console.log(decode('3a2bc')); // 'aaabbc'
console.log(decode('abc'));   // 'abc'
console.log(JSON.stringify(decode(''))); // ""

The g flag makes replace handle every count in the string. _ is a common name for an argument you don't need, here the whole match. Characters with no count in front, like the final c, don't match the pattern at all, so replace leaves them as they are, which is exactly right for a run of one.

Step 3: one digit, the natural wrong turn

It is easy to write [0-9] without the +:

Step 3

const decodeOneDigit = (encoded) =>
  encoded.replace(/([0-9])([^0-9])/g, (_, count, c) => c.repeat(Number(count)));
console.log(decodeOneDigit('3a2bc')); // 'aaabbc'
console.log(decodeOneDigit('12a'));   // '1aa'

It works for every count up to nine, so simple tests pass. With 12a, the pattern needs one digit followed by a non-digit. 1 is followed by 2, a digit, so there is no match there. 2a does match and becomes aa, and the 1 is left in the output as plain text. The result looks believable, which is what makes this bug dangerous.

With [0-9]+, the pattern grabs both digits and reads the count as 12:

JavaScript

const decode = (encoded) =>
  encoded.replace(/([0-9]+)([^0-9])/g, (_, count, c) => c.repeat(Number(count)));
console.log(decode('12a') === 'a'.repeat(12)); // true

Step 4: the round trip

The best test of a decoder is to encode something and decode it again. Here is the encoder from exercise 57:

Step 4

function encode(text) {
  let out = '';
  let i = 0;
  while (i < text.length) {
    let run = 1;
    while (text[i + run] === text[i]) run++;
    out += (run > 1 ? String(run) : '') + text[i];
    i += run;
  }
  return out;
}
const decode = (encoded) =>
  encoded.replace(/([0-9]+)([^0-9])/g, (_, count, c) => c.repeat(Number(count)));
console.log(encode('aaabbcccc'));         // '3a2b4c'
console.log(decode(encode('aaabbcccc'))); // 'aaabbcccc'
console.log(decode(encode('abcdef')));    // 'abcdef'

If decoding what you encoded always gives back the original, the two functions agree on the format.

Step 5: input that isn't valid

Step 5

const decode = (encoded) =>
  encoded.replace(/([0-9]+)([^0-9])/g, (_, count, c) => c.repeat(Number(count)));
console.log(JSON.stringify(decode('0a'))); // ""
console.log(decode('ab3'));                // 'ab3'
console.log(decode('3'));                  // '3'

A count of zero deletes the character, because repeat(0) gives ''. A count at the very end has no character after it, so nothing matches and it is left as text. No error is thrown in either case.

That quiet behavior is a problem when the encoded text comes from somewhere else. A decoder that never complains can't tell you the data was damaged. Check the shape first:

JavaScript

console.log(/^([0-9]*[^0-9])*$/.test('3a2bc')); // true
console.log(/^([0-9]*[^0-9])*$/.test('ab3'));   // false

The pattern means "the whole string is made of pieces, each one optional digits followed by one non-digit". ab3 fails because it ends with a count.

The full solution

The panel has decode, the one-digit version, and the encoder from exercise 57 for the round trip. Press Run and look at the '12a' lines, then read the checks underneath.

The answer

const decode = (encoded) =>
  encoded.replace(/([0-9]+)([^0-9])/g, (_, count, c) => c.repeat(Number(count)));

// The same idea reading a single digit. Fine until a count reaches ten.
const decodeOneDigit = (encoded) =>
  encoded.replace(/([0-9])([^0-9])/g, (_, count, c) => c.repeat(Number(count)));

// From exercise 57, so the round trip can be checked here.
function encode(text) {
  let out = '';
  let i = 0;
  while (i < text.length) {
    let run = 1;
    while (text[i + run] === text[i]) run++;
    out += (run > 1 ? String(run) : '') + text[i];
    i += run;
  }
  return out;
}

console.log("decode('3a2bc')      :", decode('3a2bc'));
console.log("decode('12a')        :", decode('12a'));
console.log("decodeOneDigit('12a'):", decodeOneDigit('12a'), '<- read 2, left the 1 behind');
console.log('round trip           :', decode(encode('aaabbcccc')));

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('a count expands its character', decode('3a2bc'), 'aaabbc');
test('text with no counts decodes to itself', decode('abc'), 'abc');
test('an empty string decodes to nothing', decode(''), '');
test('a two-digit count is read as one number', decode('12a'), 'a'.repeat(12));
test('reading only one digit gets that badly wrong', decodeOneDigit('12a'), '1aa');
test('encode and decode round-trip on text with runs', decode(encode('aaabbcccc')), 'aaabbcccc');
test('and on text with none', decode(encode('abcdef')), 'abcdef');
test('a count of zero deletes the character', decode('0a'), '');
test('a trailing count has nothing to repeat, so it is left as text', decode('ab3'), 'ab3');
test('which means a malformed input fails silently rather than loudly', decode('3'), '3');
test('so validate the shape first if the input is not yours', /^([0-9]*[^0-9])*$/.test('3a2bc'), true);

([0-9]+) rather than ([0-9]) is the entire difference between a decoder that works and one that works up to nine. decodeOneDigit('12a') returning '1aa' shows the failure mode: the leading digit is not consumed, so it lands in the output as literal text and the result is plausible enough to ship.

The silent failure on malformed input is worth noticing rather than fixing carelessly. decode('3') returns '3' because nothing matched, and decode('ab3') returns 'ab3' for the same reason. If the encoded string came from elsewhere, validate its shape and reject it — a decoder that never fails is a decoder that cannot tell you the data was corrupt.

Common mistakes

  • Matching one digit with [0-9]. Counts of ten or more break. Use [0-9]+.
  • Forgetting the g flag. Only the first count is expanded, so '3a2b' decodes to 'aaa2b'. Add g to handle every piece.
  • Trusting input you didn't encode. The decoder never throws. Validate the shape before decoding.

Try it yourself

  1. Write safeDecode(encoded) that throws an error when the shape check fails.
  2. Check decode(encode(text)) === text for every word in a short list, in one line with every.
  3. Find a string with digits in it where decode(encode(text)) is not the original text, and explain why.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.