Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string starting with a symbol n times

I am trying to replace a string starting with a specific symbol '@' with the symbol '%', but the condition is that the symbol should be at the start of the string.

For eg.

@@@hello@hi@@

should be replaced by

%%%hello@hi@@

I have come up with the regex that matches the starting '@' symbols, but I am able to replace it only once, instead of replacing it with the number of times it matched.

The code is

var str = "@@@hello@hi@@";
var exp = new RegExp('^@+', 'g');
var mystr = str.replace(exp, '%');

But, it outputs

%hello@hi@@

But, the intended output is

%%%hello@hi@@

My current solution is something like this:

var str = "@@@hello@hi@@";
var match = str.match(/^@+/g)[0];

var new_str = str.replace(match, "");

var diff_count = str.length-new_str.length;
var new_sub_str = Array(diff_count+1).join("%")

var mystr = new_sub_str + new_str;

This solution does give me the intended output, but I am worried about the performance.

Is there any better way to achieve this ?

like image 657
adi rohan Avatar asked Dec 25 '15 15:12

adi rohan


2 Answers

You can use a callback function:

var mystr = '@@@hello@hi@@'.replace(/^@+/g, function(match) {
  return Array(match.length + 1).join('%');
});
document.write(mystr);

The Array(n).join(s) construction is simply a shorthand way of repeating the string s n-1 times.

like image 73
tckmn Avatar answered Sep 30 '22 06:09

tckmn


An interesting solution without regexp:

var mystr = '@@@@@hello@hi@@'.split('').map(function(item) {
    if (item == '@' && !this.stop) {
      return '%';
    } else {
      this.stop = true;
      return item;
    }
  }, {}).join('');

  console.log(mystr);

And an alternative:

var mystr = Array.prototype.map.call('@@@@@hello@hi@@', function(item) {
    if (item == '@' && !this.stop) {
      return '%';
    } else {
      this.stop = true;
      return item;
    }
  }, {}).join('');

  console.log(mystr);
like image 32
Dmitri Pavlutin Avatar answered Sep 30 '22 06:09

Dmitri Pavlutin