본문 바로가기
FRONTEND/Javascript

[Javascript] String.split() 정리

by LAY CODER 2021. 4. 22.

String.prototype.split()

 

String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나누는 Method.

 

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

 

 

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

 

separator(Optional)

 

원본 문자열을 끊어야 할 부분을 나타내는 문자열. 실제 문자열이나 정규표현식을 받을 수 있다.

 

문자열 유형의 separator가 두 글자 이상일 경우 그 부분 문자열 전체가 일치해야 끊어진다. 

 

separator가 생략되거나 str에 등장하지 않을 경우, 반환되는 배열은 원본 문자열을 유일한 원소로 가진다. 

 

separator가 빈 문자열일 경우 str의 각각의 문자가 배열의 원소 하나씩으로 변환.

 

 

limit(Optional)

 

끊어진 문자열의 최대 개수를 나타내는 정수.

 

이 매개변수를 전달하면 배열의 원소가 limit개가 되면 멈춘다.

 

지정된 한계에 도달하기 전에 문자열의 끝까지 탐색했을 경우 limit개 미만의 원소가 있을 수도 있다.

 

남은 문자열은 새로운 배열에 포함되지 않는다.

 

 

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


// ===================================result========================================


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

 

References


developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/split

댓글