-1


I got results for both dividing substrings and replacing multiple substrings using map array. I would like to split a string with n-length before its substrings are replaced

Eg: AABBCCDDEE

MapArray : {
  AA: A,
  AB: B, <<<< this
  BB: F,
  CC: C,
  DD: D,
  EE: E
}


Result : AFCDE

I need the string to be split with length 2, so that the code won't replace 'AB', instead of replacing 'AA' and 'BB' seperately.

I can explain more if needed! Thanks in advance!

TorNadO
  • 151
  • 1
  • 6
  • 3
    Can you post an example with expected result! – ibrahim mahrir Apr 05 '17 at 18:50
  • if you just want to pick out repeating characters, you can use a regex expression such as `/([A-Z])\1+/g`, which will only match a sequence of 2 or more of the same uppercase letter. If you want to restrict it to 2, you can use `/([A-Z])\1{1}/g` which will match AA, but only the first AA of AAA, for example. – Nicolas Budig Apr 05 '17 at 18:57
  • @NicolasBudig or just `/([A-Z])\1/g` as `{1}` is default! – ibrahim mahrir Apr 05 '17 at 18:59
  • [This question](http://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) is very similar, so its answers may be helpful. – Anderson Green Apr 06 '17 at 03:43

1 Answers1

1

The code to split the string into parts of 2 character length comes from here, then it applies the map and outputs the resulting string.

var mapArray = {
  AA: 'A',
  AB: 'B',
  BB: 'F',
  CC: 'C',
  DD: 'D',
  EE: 'E'
};

var inp = "AABBCCDDEEX";
var out = inp.match(/.{1,2}/g).map(a => mapArray[a] || "-").join('');

console.log(out);
James
  • 20,957
  • 5
  • 26
  • 41