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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way I could substitute RKA with a variable? For example: str.split(/(?<=[letters])/);
See Using a variable in a javascript regex str = "YFFGRDFDRFFRGGGKBBAKBKBBK"; letters = "RKA"; re = new RegExp("(?<=[" + letters + "])"); str.split(re);
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);

Comments

0

You can pass regex in split

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

1 Comment

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])/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.