Manny19
Manny19

Reputation: 19

How can I substitute/replace numbers inside a string as a multiplier for the letter inside the string?

For example: m1 = m , m2 = mm, m3i2 = mmmii

I am trying to find a simple way to do this. Any useful methods?

This is not a homework problem. I am just practicing on my Javascript skills.

Upvotes: 0

Views: 91

Answers (6)

Manny19
Manny19

Reputation: 19

// Here is the solution I came up with.

function letTheNumberDoTheTalking(str) {
  var word = '';
  var start = 0;

  for (var next = 1; next < str.length; next += 2) {
    var letter = str[start];
    var multipliedLetter = str[start].repeat(str[next]);
    word += multipliedLetter;
    start = next + 1;
  }
  return word;
}

letTheNumberDoTheTalking('m1i1s2i1s2i1p2i1')); //==> 'mississippi'

Upvotes: 0

blu
blu

Reputation: 1

function replaceNumbers(text) {
     var match = text.match(/\D\d*/g), ans = '', i, n;

     for (i = 0; i < match.length; ++i) {
          n = Number(match[i].substr(1));
          ans += match[i].substr(0, 1).repeat(n > 0 ? n : 1);
     }

     return ans;
}

Upvotes: 0

Oriol
Oriol

Reputation: 288100

So easy with regex and repeat:

function f(str) {
  return str.replace(/(.)(\d+)/g, (_, s, n) => s.repeat(n));
}
console.log(f('m1'));   // 'm'
console.log(f('m2'));   // 'mm'
console.log(f('m3i2')); // 'mmmii'

It can behave a bit inconsistent if the string starts with a digit. You may prefer /(\D?)(\d+)/g.

Upvotes: 1

Bardy
Bardy

Reputation: 2170

ES5 Example:

var s = 'm3i2j1';
var re = /([a-z])(\d+)/g;
var matches;
var buffer = [];
while (matches = re.exec(s)) {
  buffer.push(Array(+matches[2] + 1).join(matches[1]));
}
var output = buffer.join('');

Upvotes: 0

David Steiman
David Steiman

Reputation: 3145

here in lambda style

"m2s3".split("").reduce((s,c) => isNaN(c) ? s + c : s + s[s.length-1].repeat(c-1));

mmsss

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could split the string and use the result for returning the string

var s = 'm3i2'.split(/(?=[a-z])/),
    result = s.reduce(function (r, a) {
        var i = +a.slice(1);
        while (i--) {
           r += a[0];
        }
        return r;
    }, '');

console.log(result);

Upvotes: 0

Related Questions