String.prototype.split() - JavaScript 编辑

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.  The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.  

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

str.split([separator[, limit]])

Parameters

separator Optional

The pattern describing where each split should occur.  The separator can be a simple string or it can be a regular expression.

  • The simplest case is when separator is just a single character; this is used to split a delimited string.  For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like this: myString.split("\t").
  • If separator contains multiple characters, that entire character sequence must be found in order to split.
  • If separator is omitted or does not occur in str, the returned array contains one element consisting of the entire string.
  • If separator appears at the beginning (or end) of the string, it still has the effect of splitting.  The result is an empty (i.e. zero length) string, which appears at the first (or last) position of the returned array.
  • If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters".

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

limit Optional

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 specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

  • The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
  • If limit is 0, [] is returned.

Return value

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

Description

When found, separator is removed from the string, and the substrings are returned in an array.

If separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

If the separator is an array, then that Array is coerced to a String and used as a separator.

Examples

Using split()

When the string is empty, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

const myString = ''
const splits = myString.split()

console.log(splits)

// ↪ [""]

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.

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, 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().

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

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

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

console.log(splits)

This script displays the following:

["Hello", "World.", "How"]

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

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

const myString = 'Hello 1 word. Sentence number 2.'
const splits = myString.split(/(\d)/)

console.log(splits)

This script displays the following:

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

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

Reversing a String using split()

This is not a robust way to reverse a string:

const str = 'asdfghjkl'
const strReverse = str.split('').reverse().join('')
// 'lkjhgfdsa'

// split() returns an array on which reverse() and join() can be applied

It doesn't work if the string contains grapheme clusters, even when using a unicode-aware split. (Use, for example, esrever instead.)

const str = 'résumé'
const strReverse = str.split(/(?:)/u).reverse().join('')
// => "́emuśer"

Bonus: use === operator to test if the original string was a palindrome.

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'String.prototype.split' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:102 次

字数:13049

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文