-1

I've read many question but haven't found the desired one.

I have an array of words .
How can I split the string (using regex ) by the words that in the array ?

Example

var a=['john','paul',...];
var  s = 'The beatles had two leaders , john played the guitar and paul played the bass';

My desired result is an array :

['The beatles had two leaders , ' , ' played the guitar and ','played the bass']

So basically john and paul are the splitters.

What have I tried :

I've managed to this :

var a='The beatles had two leaders , john played the guitar and paul played the bass'

var g= a.split(/(john|paul)/)
console.log(g)

Result :

["The beatles had two leaders , ", "john", " played the guitar and ", "paul", " played the bass"]

But I don't want that paul and john to be in results

Question:

How can I split a string via array of words using regex ?

NB if there are many john , split by the first.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

5

The reason john and paul were in the results is that you included them in a capture group in the regular expression. Remove the ():

var g = a.split(/john|paul/);

...or if you need to group the alternation (you don't if it's on its own like that), use a noncapturing group in the form (?:john|paul):

var g = a.split(/blah blah (?:john|paul) blah blah/);

You can form the regular expression from the array by using join and new RegExp:

var rex = new RegExp(a.join("|"));
var g = a.split(rex);

...but if there could be characters that are special in regular expressions, you'd need to escape them (probably using map) first:

var rex = new RegExp(a.map(someEscapeFunction).join("|"));
var g = a.split(rex);

This question's answers address creating someEscapeFunction, as sadly there's none built into RegExp.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875