const markerRegexp = /\((\d+)x(\d+)\)/; const decompress = (input, deep) => { let len = 0; let marker = null; do { marker = markerRegexp.exec(input); if (marker === null) { len += input.length; break; } let pos = marker.index; if (pos > 0) { len += pos; } let chars = parseInt(marker[1], 10), times = parseInt(marker[2], 10); if (!deep) { len += chars * times; } else { let str = input.substr(pos + marker[0].length, chars); len += decompress(str, true) * times; } input = input.substring(pos + marker[0].length + chars); marker = null; } while(true); return len; } const input = require('fs').readFileSync('d9.txt', 'utf8'); // no \n at EOF //const input = `(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN`; console.log(`result: \n${decompress(input, true)}`);