使用.match(regex)的JavaScript拆分字符串

前端之家收集整理的这篇文章主要介绍了使用.match(regex)的JavaScript拆分字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从Mozilla Developer Network获取功能split():

The split() method returns the new array.

When found,separator is removed from the string and the substrings
are returned in an array. If separator is not found or is omitted,the
array contains one element consisting of the entire string. If
separator is an empty string,str is converted to an array of
characters.

If separator is a regular expression that contains capturing
parentheses,then each time separator is matched,the results
(including any undefined results) of the capturing parentheses are
spliced into the output array. However,not all browsers support this
capability.

请看以下示例:

var string1 = 'one,two,three,four';
var splitString1 = string1.split(',');
console.log(splitString1); // Outputs ["one","two","three","four"]

这是一个非常干净的方法.我尝试使用正则表达式和稍微不同的字符串:

var string2 = 'one split two split three split four';
var splitString2 = string2.split(/\ split\ /);
console.log(splitString2); // Outputs ["one","four"]

这与第一个例子一样有效.在下面的示例中,我再次更改了字符串,使用了3个不同的分隔符:

var string3 = 'one split two splat three splot four';
var splitString3 = string3.split(/\ split\ |\ splat\ |\ splot\ /);
console.log(splitString3); // Outputs ["one","four"]

但是,正则表达式现在变得相对混乱.我可以对不同的分隔符进行分组,但结果将包括这些分隔符:

var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\ (split|splat|splot)\ /);
console.log(splitString4); // Outputs ["one","split","splat","splot","four"]

所以我尝试在离开组时从正则表达式中删除空格,但没有多大用处:

var string5 = 'one split two splat three splot four';
var splitString5 = string5.split(/(split|splat|splot)/);
console.log(splitString5);

虽然,当我删除正则表达式中的括号时,分隔符在分割字符串中消失了:

var string6 = 'one split two splat three splot four';
var splitString6 = string6.split(/split|splat|splot/);
console.log(splitString6); // Outputs ["one "," two "," three "," four"]

另一种方法是使用match()来过滤掉分隔符,除了我真的不明白反向前瞻是如何工作的:

var string7 = 'one split two split three split four';
var splitString7 = string7.match(/((?!split).)*/g);
console.log(splitString7); // Outputs ["one ","","plit two ","plit three ","plit four",""]

它与整个单词不匹配.说实话,我甚至不知道这里到底发生了什么.

如何在不使用结果中的分隔符的情况下使用正则表达式正确分割字符串?

解决方法

使用非捕获组作为拆分正则表达式.通过使用非捕获组,拆分匹配将不包含在结果数组中.
var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\s+(?:split|splat|splot)\s+/);
console.log(splitString4);
// Output => ["one","four"]

猜你在找的JavaScript相关文章