split string in JS by multiple letters

Viewed 360

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' ];
3 Answers

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

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

You can pass regex in split

"YFFGRDFDRFFRGGGKBBAKBKBBK".split(/[RKA]+/);
Related