String.prototype.split()

String.prototype.split()

[TOC]


捕获括号(Capturing parentheses)

如果 separator 包含捕获括号(capturing parentheses),则其匹配结果将会包含在返回的数组中。

1
2
3
4
var myString = "Hello 1 word. Sentence number 2.";
var splits = myString.split(/(\d)/);

console.log(splits);

上例输出:

1
[ "Hello ", "1", " word. Sentence number ", "2", "." ]


移出字符串中的空格

下例中,split() 方法会查找“0 或多个空白符接着的分号,再接着 0 或多个空白符”模式的字符串,找到后,就将空白符从字符串中移除,nameList 是 split 的返回数组。

1
2
3
4
5
6
7
8
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";

console.log(names);

var re = /\s*(?:;|$)\s*/;
var nameList = names.split(re);

console.log(nameList);

上例输出两行,第一行输出原始字符串,第二行输出结果数组。

1
2
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand 
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]