Javascript 我怎样才能把字符串按单词分开?
我读了很多问题,但没有找到想要的 我有一系列单词。Javascript 我怎样才能把字符串按单词分开?,javascript,regex,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 ','pla
如何用数组中的单词拆分字符串(使用正则表达式) 范例
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,则按第一个分割。john和paul出现在结果中的原因是您将他们包含在正则表达式的捕获组中。删除
()
:
…或者,如果您需要对备选方案进行分组(如果它本身就是这样,则不需要),请使用非捕获组,格式为(?:john | paul)
:
您可以使用join
和new RegExp
从数组中形成正则表达式:
var rex = new RegExp(a.join("|"));
var g = a.split(rex);
…但如果正则表达式中可能存在特殊字符,则需要首先对其进行转义(可能使用map
):
创建
someescapeffunction
,因为遗憾的是,RegExp
中没有内置任何函数。哎哟,我忘了那些捕获组。谢谢
var g = a.split(/blah blah (?:john|paul) blah blah/);
var rex = new RegExp(a.join("|"));
var g = a.split(rex);
var rex = new RegExp(a.map(someEscapeFunction).join("|"));
var g = a.split(rex);