1

I want output be like this:
['YY','RR'] with no empty elements

function pntSq(m){
    let a = m.split(/([A-Z][A-Z])/gi)
    console.log(a)
}
pntSq("YYRR")
//    output :
//    [ '', 'YY', '', 'RR', '' ]
Ayman- s.s
  • 25
  • 3

3 Answers3

0

You can match instead of using split.

function pntSq(m){
  return m.match(/[A-Z]{2}/g);
}

console.log(pntSq('YYRR'));
Andy
  • 61,948
  • 13
  • 68
  • 95
  • But your answer assumes that contiguous letters would always occur in pairs, which may not be the case. – Tim Biegeleisen Oct 13 '21 at 16:06
  • My answer assumes that the information in the question is correct otherwise I'd be here all day thinking up edge-cases that have nothing to do with the problem. – Andy Oct 13 '21 at 16:08
0

Link: regex101

This matches any 2 uppercase letters together, but note that they may be different.

[A-Z]{2}

To match the same uppercase letter 2 times. This ensures that it's the same letter repeated and not different letters.

([A-Z])\1
Luis F
  • 1
  • 1
0

JavaScript may not support splitting on lookbehinds. One workaround would be to do this in two steps. First we can replace on the following regex pattern:

([A-Z])(?!\1)(?=.)

This will capture any capital which in turn is followed by a different letter (and also not the end of the string). Then, we replace with a single space. As the second step, we simply split on space to get the output array we want.

function pntSq(m) {
    m = m.replace(/([A-Z])(?!\1)(?=.)/g, "$1 ");
    console.log(m);
    var a = m.split(/ /g);
    console.log(a);
}

pntSq("YYRRAAABBBBBCC");
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360