正则表达式替换长度为n的多个子串,从javascript中的字符串中拆分

时间:2022-05-05 21:37:48


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

我得到了分割子串的结果,并使用map数组替换了多个子串。我想在替换子串之前拆分一个n长的字符串

Eg: AABBCCDDEE

例如:AABBCCDDEE

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


Result : AFCDE

结果: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!

我需要将字符串拆分为长度为2,这样代码就不会替换'AB',而是单独替换'AA'和'BB'。如果需要,我可以解释更多!提前致谢!

1 个解决方案

#1


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.

将字符串拆分为2个字符长度的部分的代码来自此处,然后它应用地图并输出结果字符串。

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);

#1


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.

将字符串拆分为2个字符长度的部分的代码来自此处,然后它应用地图并输出结果字符串。

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);