-4

i have a string that i want to find "a" character and first "c" character and replace with "*" character, but regular expression find all "a" and "c" character i don't know how do it.

here my code:

var pattern=/[a][c]/g; //here my pattern
var str1="aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc";
var rep=str1.replace(pattern,"*");
$("p").html(rep);

2 Answers2

0

You need two replacements, because a single one replaces either a or c, depending on the first occurence in the string.

var string = "aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc",
    result = string
        .replace(/a/, '*')
        .replace(/c/, '*');

console.log(result);

An approach with a single replace and a closure over a hash table.

var string = "aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc",
    result = string.replace(/[ac]/g, (h => c => h[c] ? c : (h[c] = '*'))({}));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use capture groups for all a or c sequences but the 1st, and replace them with '*$1' ($1 is the replacement pattern for the capture group):

const str = `aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc`;

const result = str.replace(/[ac]([ac]+)/g, '*$1');

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209