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 |
瀏覽器相容性
載入中…