1

I have a string of letters and I am trying to cut them into an array using split(), but I want it to split for multiple letters. I got it to work for an individual letter:

str = "YFFGRDFDRFFRGGGKBBAKBKBBK";
str.split(/(?<=\R)/); //-> Works for only 'R'
Result->[ 'YFFGR', 'DFDR', 'FFR', 'GGGKBBAKBKBBK' ]

What I want:

str = "YFFGRDFDRFFRGGGKBBAKBKBBK";
letters =['R', 'K', 'A'];
// split by any of the three letters (R,K,A)
Result->[ 'YFFGR', 'DFDR', 'FFR', 'GGGK', 'BBA', 'K', 'BK', 'BBK' ];
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
UofF
  • 33
  • 3

3 Answers3

4

You can use "character class" group: [RKA]

Everything you put inside these brackets are alternatives in place of one character.

str = "YFFGRDFDRFFRGGGKBBAKBKBBK";
var result = str.split(/(?<=[RKA])/);

console.log(result);
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • Is there any way I could substitute RKA with a variable? For example: str.split(/(?<=[letters])/); – UofF Jul 12 '21 at 17:06
  • 1
    See [Using a variable in a javascript regex](https://stackoverflow.com/a/494046/2181514) `str = "YFFGRDFDRFFRGGGKBBAKBKBBK"; letters = "RKA"; re = new RegExp("(?<=[" + letters + "])"); str.split(re);` – freedomn-m Jul 12 '21 at 17:28
4

Beside splitting, you could match non ending characters with a single any character sign.

const
    str = "YFFGRDFDRFFRGGGKBBAKBKBBK",
    result = str.match(/[^RKA]*./g);

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

You can pass regex in split

"YFFGRDFDRFFRGGGKBBAKBKBBK".split(/[RKA]+/);
  • OP is already passing a regex in the split `str.split(/(?<=\R)/);` - they're trying to find *which* regex will match they're requirement. Which is: `/(?<=[RKA])/` – freedomn-m Jul 12 '21 at 16:52