如何用文字分割字符串?

时间:2018-01-07 12:13:26

标签: javascript regex

我读了很多问题,但没找到想要的问题。

我有一系列的话 如何通过数组中的单词拆分字符串(使用正则表达式)?

实施例

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

我想要的结果是一个数组:

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

所以基本上约翰和保罗都是分手。

我尝试了什么:

我成功了:

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)

结果:

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

但我不希望保罗和约翰成为结果

问题:

如何使用正则表达式通过单词数组拆分字符串?

注意是否有很多john,由第一个分开。

1 个答案:

答案 0 :(得分:5)

约翰和保罗在结果中的原因是你将它们包含在正则表达式的捕获组中。删除()

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

...或者如果您需要对交替进行分组(如果它本身就是这样),请使用(?:john|paul)形式的非捕获组:

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

您可以使用joinnew RegExp从数组中构建正则表达式:

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

...但是如果可能存在正则表达式中特殊的字符,则需要先将它们转义(可能使用map):

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

This question's answers地址创建someEscapeFunction,遗憾的是RegExp没有内置。