Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. String
  6. split()

String.prototype.split()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Thesplit() method ofString 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

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

Syntax

js
split(separator)split(separator, limit)

Parameters

separator

The pattern describing where each split should occur. Can beundefined, a string, or an object with aSymbol.split method — the typical example being aregular expression. Omittingseparator or passingundefined causessplit() to return an array with the calling string as a single element. All values that are notundefined or objects with a[Symbol.split]() method arecoerced to strings.

limitOptional

A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specifiedseparator, but stops whenlimit entries have been placed in the array. Any leftover text is not included in the array at all.

  • The array may contain fewer entries thanlimit if the end of the string is reached before the limit is reached.
  • Iflimit is0,[] is returned.

Return value

Ifseparator is a string, anArray of strings is returned, split at each point where theseparator occurs in the given string.

Ifseparator is a regex, the returnedArray also contains thecaptured groups for each separator match; see below for details. The capturing groups may be unmatched, in which case they areundefined in the array.

Ifseparator has a custom[Symbol.split]() method, its return value is directly returned.

Description

Ifseparator is a non-empty string, the target string is split by all matches of theseparator without includingseparator in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, likemyString.split("\t"). Ifseparator contains multiple characters, that entire character sequence must be found in order to split. Ifseparator 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. Ifseparator does not occur instr, the returned array contains one element consisting of the entire string.

Ifseparator 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.

Note:"".split("") is therefore the only way to produce an empty array when a string is passed asseparator andlimit is not0.

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

Ifseparator 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 isUnicode-aware.

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

Ifseparator is a regular expression with capturing groups, then each timeseparator matches, the captured groups (including anyundefined results) are spliced into the output array. This behavior is specified by the regexp'sSymbol.split method.

Ifseparator is an object with aSymbol.split method, that method is called with the target string andlimit as arguments, andthis set to the object. Its return value becomes the return value ofsplit.

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

Examples

Using 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-emptyconsole.log(emptyString.split("a"));// [""]// string and separator are both empty stringsconsole.log(emptyString.split(emptyString));// []

The following example defines a function that splits a string into an array of stringsusingseparator. After splitting the string, the function logsmessages indicating the original string (before the split), the separator used, thenumber 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

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

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 logsthe 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

In the following example,split() looks for spaces in a string and returnsthe 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" ]

Splitting with aRegExp to include parts of the separator in the result

Ifseparator is a regular expression that contains capturingparentheses( ), 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", "." ]

Note:\d matches thecharacter class for digits between 0 and 9.

Using a custom splitter

An object with aSymbol.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" ]

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

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp