Split string by certain letters while also skipping certain letters

Viewed 71

I wrote some code to split a given string by certain letters. Below is the code:

let split_by_each_letter_here = "KM";
let re = new RegExp("(?<=[" + split_by_each_letter_here + "])");
let ans = "YGMGPKPDDFLKJJ".split(re);
returns -> [ 'YGM', 'GPK', 'PDDFLK', 'JJ' ]

Notice how each split in the array is at either a 'K' or an 'M' (specified in split_by_each_letter_here).

I want to modify this code so that every time there is a 'P' in my string directly following one of the split letters ('K' or 'M'), the string does not split. For example:

let str = "YGMGPKPDDFLKJJ";
// the array should be ['YGM', 'GPKPDDFLK', 'JJ'];

Notice that since the first 'K' is directly followed by a 'P', the string does not split there. However, it does split at the second 'K' because there is no 'P' directly following that 'K'.

Is my desired output possible using RegEx? How would I go about doing this? Thanks!

1 Answers

We can try using match here as follows:

var input = "YGMGPKPDDFLKJJ";
var matches = input.match(/.+?(?:[KM](?!P)|$)/g);
console.log(matches);

Here is an explanation of the regex pattern:

.+?        match all content up to the nearest
(?:
    [KM]   the letters K or M
    (?!P)  which are NOT immediately followed by P
    |      OR
    $      the end of the input (consume everything until the end)
)
Related