0

javascript, what is the best way to replace following two scenario. It is possible to use replace and add regex to do this, if yes, how?

I want to convert "aaa.bbb.ccc" TO  "aaa.bbb.*"
I want to convert "aaa.bbb.ccc.ddd.eee" TO "aaa.bbb.*.ddd.*"
Elizabeth
  • 47
  • 9

1 Answers1

0

var map = 'qwertyuiopasdfghjklzxcvbnm'.split('');
var rand = function(){
    var len = map.length,
        arr = [],
        i;
    for (i = 0; i < 3; i++){
        arr.push(map[Math.floor(Math.random()*len)]);
    }
    return arr.join('');
};
var randStr = [rand(), rand()];

/* ASSUME above code is how you get random string */

var string = 'aaa.bbb.' + randStr[0] + '.ddd.' + randStr[1];

// use new RegExp() to parse string as regular expression
var regexp = new RegExp(randStr[0] + '|' + randStr[1], 'gi');

console.log(string.replace(regexp, '*'));

Read more about new RegExp() here (easy one), here (detailed one) and here (working example).

You should be able to apply this concept in your code now.

yqlim
  • 6,898
  • 3
  • 19
  • 43
  • ccc and eee are random characters, what we sure it we have '.' between those characters – Elizabeth Jun 22 '17 at 16:32
  • Thanks for reply, the thing is , aaa, bbb, ccc,ddd, all of them are randomly generated, the only thing which is certain is '.' – Elizabeth Jun 22 '17 at 16:56
  • So, the question can be: to replace after second existence of '.' and to replace between second '.' and third '.' – Elizabeth Jun 22 '17 at 16:57