Search code examples
javascriptregexstring

Split string by all words except specified words Regex JavaScript


I have a string

const s = 'pong-ping-bink-ping-pong-ping-donk';

I want to split it by all words other than ping or pong with regex.

For this string I expect an array, splitted by -bink- and -donk-

"pong-ping",
"ping-pong-ping"

Another example

const s = 'ping-pong-ping-pong-fong-song-pong-bing';

"ping-pong-ping-pong",
"pong"

This is what I am doing now

const s = 'ping-pong-ping-pong-fong-song-pong-bing';

const r = /-(?!ping|?!pong)-/g;
const result = s.split(r);

console.log(result);

I'm clearly far from the goal. It returns Uncaught SyntaxError: Invalid regular expression: Nothing to repeat

What should I do?


Solution

  • You may use this regex for splitting:

    /(?:-(?!p[io]ng)\w+)+-?/g
    

    Then to filter out empty result just use:

    str.split(/(?:-(?!p[io]ng)\w+)+-?/g).filter(Boolean)
    

    RegEx Demo

    Code:

    const rx = /(?:-(?!p[io]ng)\w+)+-?/g;
    
    function splt(s) {
        return s.split(rx).filter(Boolean);
    }
    
    const p = 'pong-ping-bink-ping-pong-ping-donk';
    console.log(splt(p));
    
    const r = 'ping-pong-ping-pong-fong-song-pong-bing';
    console.log(splt(r));

    RegEx Details:

    • (?:: Start a non-capture group
      • -: Match a -
      • (?!p[io]ng): Negative lookahead to assert that we don't have ping or pong on the rights side of the current position
      • \w+: Match 1+ of word characters
    • )+: Close non-capture group and repeat this group 1+ times
    • -?: Match - optionally