2
\$\begingroup\$

This replaces numbers with the character that appears next to them ('number' times). Is there a a more elegant or shorter way to do this?

var decode = function(str, result) {
    var regex = /\d+/,
        number = regex.exec(str);

    if (number === null) {
        return str;
    }

    var start =  number.index,
        end = number[0].length + start - 1,
        str = str.replace(/\d+/, ""),
        repeat = str.charAt(start);

    result += str.substring(0, start);
    for (var i = 0; i < number[0] - 1; i++) {
        result += repeat;
    }
    result += str.substring(start, str.length);
    number = regex.exec(result);

    if (number === null) {
        return result;
    } else {
        return decode(result, "");
    }
};

var str = "bob2b11a";
console.log(decode(str, ""));
// "bobbbaaaaaaaaaaa"
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

The basic concept

  • Utilize string replace with regular expression
  • Utilize new Array Creation with join

The code

function decode (str) {
    return str.replace(/(\d+)(\w)/g, 
        function(m,n,c){
            return new Array( parseInt(n,10)+1 ).join(c);
        }
    );
}
\$\endgroup\$
5
  • \$\begingroup\$ Clever. I forgot about [].join... \$\endgroup\$
    – beatgammit
    Nov 20, 2012 at 20:11
  • \$\begingroup\$ @epascarello please can you tell me in the function, where/how do m, n, c get populated with the values? How does that work? Many thanks in advance. \$\endgroup\$
    – mtwallet
    Mar 7, 2019 at 14:29
  • \$\begingroup\$ @mtwallet read documentation for replace developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… \$\endgroup\$ Mar 7, 2019 at 14:31
  • \$\begingroup\$ @epascarello thanks, I looked at w3schools.com/jsref/jsref_replace.asp which didn't have the same level of detail \$\endgroup\$
    – mtwallet
    Mar 8, 2019 at 15:10
  • \$\begingroup\$ Avoid w3schools since their documentation lacks in a bunch of areas. \$\endgroup\$ Mar 8, 2019 at 17:41
2
\$\begingroup\$

From my answer on Stack Overflow: https://stackoverflow.com/a/13481139/538551

Simply use String.replace():

function decode(str) {
    return str.replace(/(\d+)([a-zA-A])/g, function (match, num, letter) {
        var ret = '', i;
        for (i = 0; i < parseInt(num, 10); i++) {
            ret += letter;
        }
        return ret;
    });
}
\$\endgroup\$
1
  • \$\begingroup\$ Yeah, but this is the better place, so I wanted to provide it here just for completeness. @epascarello's answer will probably be better. \$\endgroup\$
    – beatgammit
    Nov 20, 2012 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.