在 Mozilla 开发者网络中,函数 split()
返回新的数组。
当分隔符被找到时,它会从字符串中移除,并将子字符串返回到一个数组中。如果没有找到分隔符或省略了,则该数组包含一个元素,该元素由整个字符串组成。如果分隔符是空字符串,则 str 被转换为字符数组。
如果分隔符是一个包含捕获括号的正则表达式,则每次匹配到分隔符时,捕获括号的结果(包括任何未定义的结果)都会插入到输出数组中。但是,并非所有浏览器都支持此功能。
以下是一个示例:
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", "two", "three", "four"]
这个例子的效果与第一个例子一样。在下面的例子中,我再次更改了字符串,并使用了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"]
然而,现在正则表达式变得相对混乱。我可以将不同的定界符进行分组,但结果将包含这些定界符:
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"]
因此,我尝试从正则表达式中去除空格,同时保留组,但没有什么效果:
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", ""]
首先,它并不会匹配整个单词。老实说,我甚至不知道这里到底发生了什么。
如何使用正则表达式正确地拆分字符串,而不在结果中包含分隔符?
string5.split(/\s?(split|splat|splot)\s?/)
. - SeinopSys/ split | splat | splot /
。 - SamWhan