Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading