Help us test MDN's new front-end: https://discourse.mozilla.org/t/help-us-test-mdns-new-react-front-end-beta/42593

이 번역은 완료되지 않았습니다. 이 문서를 번역해 주세요.

split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

구문

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

주의: 구분자로 빈 문자열("")을 제공하면, 사용자가 인식하는 문자 하나(grapheme cluster) 또는 유니코드 문자(코드포인트) 하나씩으로 나누는 것이 아니라, UTF-16 코드유닛으로 나누게 되며 써로게이트 페어surrogate pair가 망가질 수 있습니다. Stack Overflow의 이 질문(How do you get a string to a character array in JavaScript?)을 참고하세요.

매개변수

separator Optional
Specifies the string which denotes the points at which each split should occur. The separator is treated as a string or as a regular expression. If a plain-text separator contains more than one character, that entire string must be found to represent a split point. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array having one element for each character of str.
limit Optional

Integer specifying a limit on the number of splits to be found. When this parameter is provided, the split() method splits the string at each occurrence of the specified separator but stops when limit entries have been placed into the array. It may still contain fewer entries than limit if the end of the string is reached before the specified limit is reached. The left-over text is not returned in the new array.

반환 값

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

설명

When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters. If separator appears at the beginning or end of the string, or both, the array begins, ends, or both begins and ends, respectively, with an empty string. Thus, if the string consists solely of one instance of separator, the array consists of two empty strings.

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

주의: if separator is an array, then Array is coerced to String and used as separator.

주의: 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.

예제

Using split()

The following example defines a function that splits a string into an array of strings using the specified 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) {
  var 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(' / '));
}

var tempestString = 'Oh brave new world that has such people in it.';
var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';

var space = ' ';
var 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

문자열에서 공백 제거하기

In the following example, split() looks for 0 or more spaces followed by a semicolon followed by 0 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().

var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';

console.log(names);

var re = /\s*(?:;|$)\s*/;
var 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", "" ]

나눈 문자열 수 제한하기

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

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

console.log(splits);

This script displays the following:

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

RegExp를 사용해 구분자도 결과에 포함하기

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

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

console.log(splits);

This script displays the following:

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

배열을 구분자로 사용하기

var myString = 'this|is|a|Test';
var splits = myString.split(['|']);

console.log(splits); //["this", "is", "a", "Test"]

var myString = 'ca,bc,a,bca,bca,bc';

var splits = myString.split(['a','b']); 
// myString.split(['a','b']) is same as myString.split(String(['a','b'])) 

console.log(splits);  //["c", "c,", "c", "c", "c"]

split()으로 문자열 뒤집기

This is not a robust way to reverse a string:

var str = 'asdfghjkl';
var 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).

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

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

명세

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.1.
ECMAScript 5.1 (ECMA-262)
The definition of 'String.prototype.split' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.split' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'String.prototype.split' in that specification.
Draft  

브라우저 호환성

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
splitChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

같이 보기

문서 태그 및 공헌자

이 페이지의 공헌자: alattalatta, mdnwebdocs-bot, yuntaek
최종 변경자: alattalatta,