Aud*_*low 10 javascript regex split
来自Mozilla开发者网络的功能split():
split()方法返回新数组.
找到后,将从字符串中删除分隔符,并在数组中返回子字符串.如果未找到separator或省略该分隔符,则该数组包含一个由整个字符串组成的元素.如果separator是空字符串,则str将转换为字符数组.
如果separator是包含捕获括号的正则表达式,则每次匹配时,捕获括号的结果(包括任何未定义的结果)都会拼接到输出数组中.但是,并非所有浏览器都支持此功能.
请看以下示例:
var string1 = 'one, two, three, four';
var splitString1 = string1.split(', ');
console.log(splitString1); // Outputs ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)
这是一个非常干净的方法.我尝试使用正则表达式和稍微不同的字符串:
var string2 = 'one split two split three split four';
var splitString2 = string2.split(/\ split\ /);
console.log(splitString2); // Outputs ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)
这与第一个例子一样有效.在下面的示例中,我再次更改了字符串,使用了3个不同的分隔符:
var string3 = 'one split two splat three splot four';
var splitString3 = string3.split(/\ split\ |\ splat\ |\ splot\ /);
console.log(splitString3); // Outputs ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)
但是,正则表达式现在变得相对混乱.我可以对不同的分隔符进行分组,但结果将包括这些分隔符:
var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\ (split|splat|splot)\ /);
console.log(splitString4); // Outputs ["one", "split", "two", "splat", "three", "splot", "four"]
Run Code Online (Sandbox Code Playgroud)
所以我尝试在离开组时从正则表达式中删除空格,但没有多大用处:
var string5 = 'one split two splat three splot four';
var splitString5 = string5.split(/(split|splat|splot)/);
console.log(splitString5);
Run Code Online (Sandbox Code Playgroud)
虽然,当我删除正则表达式中的括号时,分隔符在分割字符串中消失了:
var string6 = 'one split two splat three splot four';
var splitString6 = string6.split(/split|splat|splot/);
console.log(splitString6); // Outputs ["one ", " two ", " three ", " four"]
Run Code Online (Sandbox Code Playgroud)
另一种方法是用来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", ""]
Run Code Online (Sandbox Code Playgroud)
它与整个单词不匹配.说实话,我甚至不知道这里到底发生了什么.
如何在不使用结果中的分隔符的情况下使用正则表达式正确分割字符串?
anu*_*ava 15
使用非捕获组作为拆分正则表达式.通过使用非捕获组,拆分匹配将不包含在结果数组中.
var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\s+(?:split|splat|splot)\s+/);
console.log(splitString4);Run Code Online (Sandbox Code Playgroud)
// Output => ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)