Scriptdrill

Level 3: Strings and dates Exercise 44 of 76 Free

Run-length encoding

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Shorten `s` by replacing every run of the same character with the character followed by the length of the run. A character that stands alone gets no number, so `"aaabbc"` becomes `"a3b2c"`. Runs are case sensitive and only count neighbors: `"aabaa"` is `"a2ba2"`. `s` contains no digits. An empty string returns `""`.

What this exercise teaches

A run ends where the next character differs, so the output is written at that moment and the count restarts. Counting how often each character occurs in the whole string is a different question: it would merge the two separate runs of a in aabaa.

A hint if you get stuck

Walk the string and count how long the current character repeats. When the next character differs (or the string ends), append the character and, if the count is above 1, the count.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Strings and dates