Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the next function:

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"

So It replaces the numbers with the character that appears next to them ('number' times). There is a more elegant or shorter way to do this?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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);
        }
    );
}
share|improve this answer
    
Clever. I forgot about [].join... –  tjameson Nov 20 '12 at 20:11

From my answer on Stack Overflow: http://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;
    });
}
share|improve this answer
    
Hehe, I have already accept your answer in SO. –  enrmarc Nov 20 '12 at 20:09
    
Yeah, but this is the better place, so I wanted to provide it here just for completeness. @epascarello's answer will probably be better. –  tjameson Nov 20 '12 at 20:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.