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-


Another example

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


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


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

What should I do?


  • You may use this regex for splitting:


    Then to filter out empty result just use:


    RegEx Demo


    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';
    const r = 'ping-pong-ping-pong-fong-song-pong-bing';

    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