String.prototype.split()
split() 方法用于 String 值,它接受一个模式(pattern),通过搜索该模式来将字符串分割成一个有序的子字符串列表,将这些子字符串放入一个数组中,然后返回该数组。
试一试
const str = "The quick brown fox jumps over the lazy dog.";
const words = str.split(" ");
console.log(words[3]);
// Expected output: "fox"
const chars = str.split("");
console.log(chars[8]);
// Expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
语法
split(separator)
split(separator, limit)
参数
separator-
描述每次分割应该发生位置的模式。可以是
undefined、字符串,或带有Symbol.split方法的对象 —— 最典型的例子是 正则表达式。省略separator或传入undefined会导致split()返回一个包含调用字符串作为单个元素的数组。所有非undefined或不具有[Symbol.split]()方法的对象都会被 强制转换为字符串。 limit可选-
一个非负整数,指定要包含在数组中的子字符串的最大数量。如果提供,则在指定
separator的每次出现时分割字符串,但当数组中已包含limit个元素时停止。任何剩余的文本都不会包含在数组中。- 如果字符串在达到
limit之前结束,则数组可能包含的条目少于limit。 - 如果
limit为0,则返回[]。
- 如果字符串在达到
返回值
如果 separator 是一个字符串,则返回一个字符串 Array,该字符串在 separator 在给定字符串中出现的每个点都被分割。
如果 separator 是一个正则表达式,返回的 Array 还将包含每个分隔符匹配的 捕获组;有关详细信息,请参阅下文。捕获组可能不匹配,在这种情况下,它们在数组中为 undefined。
如果 separator 具有自定义的 [Symbol.split]() 方法,则直接返回其返回值。
描述
如果 separator 是一个非空字符串,则目标字符串将根据 separator 的所有匹配项进行分割,而不将 separator 包含在结果中。例如,一个包含制表符分隔值(TSV)的字符串可以通过将制表符字符作为分隔符来解析,例如 myString.split("\t")。如果 separator 包含多个字符,则必须找到整个字符序列才能进行分割。如果 separator 出现在字符串的开头(或结尾),它仍然会产生分割效果,导致在返回数组的第一个(或最后一个)位置出现一个空(即零长度)字符串。如果 separator 未出现在 str 中,则返回的数组将包含一个由整个字符串组成的元素。
如果 separator 是一个空字符串 (""),str 将被转换为其每个 UTF-16 "字符"组成的数组,在生成的字符串的两端没有空字符串。
注意:因此,当字符串作为 separator 传递且 limit 不为 0 时,"".split("") 是产生空数组的唯一方法。
警告:当空字符串 ("") 用作分隔符时,字符串不会按用户感知的字符(字素簇)或 Unicode 字符(码点)进行分割,而是按 UTF-16 码元进行分割。这会破坏代理对。请参阅 Stack Overflow 上的 "如何在 JavaScript 中将字符串转换为字符数组?"。
如果 separator 是一个匹配空字符串的正则表达式,是否按 UTF-16 码元或 Unicode 码点进行分割取决于正则表达式是否为 Unicode 感知。
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]
如果 separator 是一个带有捕获组的正则表达式,那么每次 separator 匹配时,捕获组(包括任何 undefined 结果)都会插入到输出数组中。此行为由正则表达式的 Symbol.split 方法指定。
如果 separator 是一个带有 Symbol.split 方法的对象,则该方法将使用目标字符串和 limit 作为参数进行调用,并且 this 将设置为该对象。它的返回值将成为 split 的返回值。
任何其他值都将在被用作分隔符之前被强制转换为字符串。
示例
使用 split()
当字符串为空且指定了非空分隔符时,split() 返回 [""]。如果字符串和分隔符都是空字符串,则返回一个空数组。
const emptyString = "";
// string is empty and separator is non-empty
console.log(emptyString.split("a"));
// [""]
// string and separator are both empty strings
console.log(emptyString.split(emptyString));
// []
以下示例定义了一个函数,该函数使用 separator 将字符串分割成字符串数组。分割字符串后,函数会记录消息,指示原始字符串(分割前)、使用的分隔符、数组中的元素数量以及各个数组元素。
function splitString(stringToSplit, separator) {
const arrayOfStrings = stringToSplit.split(separator);
console.log("The original string is:", stringToSplit);
console.log("The separator is:", separator);
console.log(
"The array has",
arrayOfStrings.length,
"elements:",
arrayOfStrings.join(" / "),
);
}
const tempestString = "Oh brave new world that has such people in it.";
const monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
const space = " ";
const comma = ",";
splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
此示例产生以下输出
The original string is: "Oh brave new world that has such people in it." The separator is: " " The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. The original string is: "Oh brave new world that has such people in it." The separator is: "undefined" The array has 1 elements: Oh brave new world that has such people in it. The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
从字符串中移除空格
在下面的示例中,split() 查找零个或多个空格,后跟分号,后跟零个或多个空格——找到后,会从字符串中移除空格和分号。nameList 是 split() 返回的数组。
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
console.log(names);
const re = /\s*(?:;|$)\s*/;
const nameList = names.split(re);
console.log(nameList);
这会记录两行;第一行记录原始字符串,第二行记录结果数组。
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand [ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
返回有限数量的分割
在下面的示例中,split() 在字符串中查找空格,并返回找到的前 3 个分割。
const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);
console.log(splits); // [ "Hello", "World.", "How" ]
使用 RegExp 分割以将分隔符的一部分包含在结果中
如果 separator 是一个包含捕获括号 ( ) 的正则表达式,则匹配的结果会包含在数组中。
const myString = "Hello 1 word. Sentence number 2.";
const splits = myString.split(/(\d)/);
console.log(splits);
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
注意: \d 匹配 0 到 9 之间的数字的字符类。
使用自定义分割器
一个带有 Symbol.split 方法的对象可以用作具有自定义行为的分割器。
以下示例使用一个由递增数字组成的内部状态来分割字符串
const splitByNumber = {
[Symbol.split](str) {
let num = 1;
let pos = 0;
const result = [];
while (pos < str.length) {
const matchPos = str.indexOf(num, pos);
if (matchPos === -1) {
result.push(str.substring(pos));
break;
}
result.push(str.substring(pos, matchPos));
pos = matchPos + String(num).length;
num++;
}
return result;
},
};
const myString = "a1bc2c5d3e4f";
console.log(myString.split(splitByNumber)); // [ "a", "bc", "c5d", "e", "f" ]
以下示例使用内部状态来强制执行特定行为,并确保生成“有效”结果。
const DELIMITER = ";";
// Split the commands, but remove any invalid or unnecessary values.
const splitCommands = {
[Symbol.split](str, lim) {
const results = [];
const state = {
on: false,
brightness: {
current: 2,
min: 1,
max: 3,
},
};
let pos = 0;
let matchPos = str.indexOf(DELIMITER, pos);
while (matchPos !== -1) {
const subString = str.slice(pos, matchPos).trim();
switch (subString) {
case "light on":
// If the `on` state is already true, do nothing.
if (!state.on) {
state.on = true;
results.push(subString);
}
break;
case "light off":
// If the `on` state is already false, do nothing.
if (state.on) {
state.on = false;
results.push(subString);
}
break;
case "brightness up":
// Enforce a brightness maximum.
if (state.brightness.current < state.brightness.max) {
state.brightness.current += 1;
results.push(subString);
}
break;
case "brightness down":
// Enforce a brightness minimum.
if (state.brightness.current > state.brightness.min) {
state.brightness.current -= 1;
results.push(subString);
}
break;
}
if (results.length === lim) {
break;
}
pos = matchPos + DELIMITER.length;
matchPos = str.indexOf(DELIMITER, pos);
}
// If we broke early due to reaching the split `lim`, don't add the remaining commands.
if (results.length < lim) {
results.push(str.slice(pos).trim());
}
return results;
},
};
const commands =
"light on; brightness up; brightness up; brightness up; light on; brightness down; brightness down; light off";
console.log(commands.split(splitCommands, 3)); // ["light on", "brightness up", "brightness down"]
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.split |
浏览器兼容性
加载中…