String.prototype.split()

String 值的 split() 方法接受一个模式,并通过搜索该模式将该字符串划分为一个有序的子字符串列表,将这些子字符串放入一个数组中,然后返回该数组。

¥The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Try it

语法

¥Syntax

js
split(separator)
split(separator, limit)

参数

¥Parameters

separator

描述每次分割应该发生的位置的模式。可以是 undefined、字符串或具有 Symbol.split 方法的对象 - 典型示例是 regular expression。省略 separator 或传递 undefined 会导致 split() 返回一个数组,其中调用字符串作为单个元素。所有非 undefined 的值或具有 @@split 方法的对象都是 强制为字符串

limit Optional

一个非负整数,指定数组中包含的子字符串数量的限制。如果提供,则在每次出现指定的 separator 时分割字符串,但在数组中放入 limit 条目时停止。任何剩余文本根本不包含在数组中。

  • 如果在达到限制之前到达字符串末尾,则数组包含的条目数可能少于 limit
  • 如果 limit0,则返回 []

返回值

¥Return value

Array 个字符串,在给定字符串中出现 separator 的每个点处进行分割。

¥An Array of strings, split at each point where the separator occurs in the given string.

描述

¥Description

如果 separator 是非空字符串,则目标字符串将按 separator 的所有匹配项进行分割,结果中不包括 separator。例如,可以通过传递制表符作为分隔符来解析包含制表符分隔值 (TSV) 的字符串,例如 myString.split("\t")。如果 separator 包含多个字符,则必须找到整个字符序列才能拆分。如果 separator 出现在字符串的开头(或结尾),它仍然具有分割的效果,导致返回数组的第一个(或最后一个)位置出现一个空(即零长度)字符串。如果 separator 没有出现在 str 中,则返回的数组包含一个由整个字符串组成的元素。

¥If separator is a non-empty string, the target string is split by all matches of the separator without including separator in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like myString.split("\t"). If separator contains multiple characters, that entire character sequence must be found in order to split. If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If separator does not occur in str, the returned array contains one element consisting of the entire string.

如果 separator 是空字符串 (""),则 str 将转换为其每个 UTF-16 "characters" 的数组,结果字符串的两端都没有空字符串。

¥If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.

注意:因此,当字符串作为 separator 传递且 limit 不是 0 时,"".split("") 是生成空数组的唯一方法。

¥Note: "".split("") is therefore the only way to produce an empty array when a string is passed as separator and limit is not 0.

警告:当使用空字符串("")作为分隔符时,字符串不会按用户感知的字符(字素簇)或 unicode 字符(代码点)进行拆分,而是按 UTF-16 代码单元进行拆分。这会摧毁 代理对。参见 StackOverflow 上的 "如何在 JavaScript 中将字符串获取到字符数组?"

¥Warning: When the empty string ("") is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (code points), but by UTF-16 code units. This destroys surrogate pairs. See "How do you get a string to a character array in JavaScript?" on StackOverflow.

如果 separator 是匹配空字符串的正则表达式,则匹配是按 UTF-16 代码单元还是 Unicode 代码点拆分取决于正则表达式是否为 Unicode 感知

¥If separator is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is Unicode-aware.

js
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]

如果 separator 是带有捕获组的正则表达式,则每次 separator 匹配时,捕获的组(包括任何 undefined 结果)都会拼接到输出数组中。此行为由正则表达式的 Symbol.split 方法指定。

¥If separator is a regular expression with capturing groups, then each time separator matches, the captured groups (including any undefined results) are spliced into the output array. This behavior is specified by the regexp's Symbol.split method.

如果 separator 是具有 Symbol.split 方法的对象,则使用目标字符串和 limit 作为参数来调用该方法,并将 this 设置为该对象。它的返回值成为 split 的返回值。

¥If separator is an object with a Symbol.split method, that method is called with the target string and limit as arguments, and this set to the object. Its return value becomes the return value of split.

任何其他值在用作分隔符之前都将被强制转换为字符串。

¥Any other value will be coerced to a string before being used as separator.

示例

¥Examples

使用 split()

¥Using split()

当字符串为空并且指定了非空分隔符时,split() 返回 [""]。如果字符串和分隔符都是空字符串,则返回空数组。

¥When the string is empty and a non-empty separator is specified, split() returns [""]. If the string and separator are both empty strings, an empty array is returned.

js
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 将字符串拆分为字符串数组。分割字符串后,该函数会记录消息,指示原始字符串(分割之前)、使用的分隔符、数组中的元素数量以及各个数组元素。

¥The following example defines a function that splits a string into an array of strings using separator. After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

js
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);

此示例产生以下输出:

¥This example produces the following output:

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

从字符串中删除空格

¥Removing spaces from a string

在下面的示例中,split() 查找零个或多个空格,后跟分号,后跟零个或多个空格,找到后,从字符串中删除空格和分号。nameList 是作为 split() 返回的结果的数组。

¥In the following example, split() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and the semicolon from the string. nameList is the array returned as a result of split().

js
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);

这会记录两行;第一行记录原始字符串,第二行记录结果数组。

¥This logs two lines; the first line logs the original string, and the second line logs the resulting array.

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

返回有限数量的分割

¥Returning a limited number of splits

在以下示例中,split() 在字符串中查找空格并返回它找到的前 3 个分割。

¥In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.

js
const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);

console.log(splits); // [ "Hello", "World.", "How" ]

使用 RegExp 进行拆分以在结果中包含部分分隔符

¥Splitting with a RegExp to include parts of the separator in the result

如果 separator 是包含捕获括号 ( ) 的正则表达式,则匹配结果将包含在数组中。

¥If separator is a regular expression that contains capturing parentheses ( ), matched results are included in the array.

js
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 之间的数字。

¥Note: \d matches the character class for digits between 0 and 9.

使用自定义分离器

¥Using a custom splitter

具有 Symbol.split 方法的对象可以用作具有自定义行为的拆分器。

¥An object with a Symbol.split method can be used as a splitter with custom behavior.

以下示例使用由递增数字组成的内部状态分割字符串:

¥The following example splits a string using an internal state consisting of an incrementing number:

js
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" ]

以下示例使用内部状态来强制执行某些行为,并确保生成 "valid" 结果。

¥The following example uses an internal state to enforce certain behavior, and to ensure a "valid" result is produced.

js
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"]

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.split

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看