본문 바로가기
개발 관련 지식/JS

split : 문자열 분할 함수

by 권태일1147 2020. 3. 5.

split은 특정 문자열을 제거하고 남은 문자열을 배열로 반환한다.

 

split의 기본형태

str.split(separator, limit)

separator는 str을 끊어야하는 부분을 나타내는 문자열

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

separator와 limit 둘다 선택적으로 사용 가능하다. 다만 limit은 separator가 있을 때만 사용이 가능하다.

또한 separator는 정규표현식을 넣을 수 있다.

 

 

separator에 아무것도 입력하지 않았을 경우

원래의 문자열이 배열에 담겨서 나온다.

const str = 'abcdefg';
const splitedStr = str.split();

console.log(splitedStr);

// ["abcdefg"]

 

 

separator에 빈 문자열("" , "  ")을 입력할 경우

const str1 = 'aabbcc ddeeff';
const splitedStr1 = str1.split(""); // 문자열의 요소 하나하나 전부 분할

console.log(splitedStr1);

// ["a","a","b","b","c","c"," ","d","d","e","e","f","f"]



const str2 = 'aabbcc ddeeff';
const splitedStr2 = str2.split(" ");  // 띄어쓰기를 기준으로 문자열을 분할.

console.log(splitedStr2);

// ["aabbcc", "ddeeff"]

 

 

separator가 원본 문자열의 맨 앞이나 맨 뒤에 나타날 경우

반환되는 배열도 빈 문자열("")로 시작하거나 끝난다.

const str = 'Hello, Welcome to my world and my page';
const startStr = 'Hello,'
const splitedStr = str.split(startStr);

console.log(splitedStr);

// [""," Welcome to my world and my page"]



const str1 = 'Hello, Welcome to my world and my page';
const endStr = 'page'
const splitedStr1 = str1.split(endStr);

console.log(splitedStr1);

// ["Hello, Welcome to my world and my ", ""]

 

 

split의 separator는 정규표현식도 받는다.

const str = 'Hello, Welcome to my world and my page';
const rex = /MY/i
const splitedStr = str.split(rex);

console.log(splitedStr);

// ["Hello, Welcome to ", " world and ", " page"]
// 정규식 플래그 g(global)은 자동 적용 되는 듯.

 

 

limit를 적용할 경우.

반환된 배열의 최대 개수가 limit만큼 생성된다.

const str = 'Hello, Welcome to my world and my page';
const rex = /MY/i

let splitedStr = str.split(rex, 1);
console.log(splitedStr);
// ["Hello, Welcome to "]


splitedStr = str.split(rex, 2);
console.log(splitedStr);
// ["Hello, Welcome to ", " world and "]


splitedStr = str.split(rex, 3);
console.log(splitedStr);
// ["Hello, Welcome to ", " world and ", " page"]


splitedStr = str.split(rex, 4);
console.log(splitedStr);
// ["Hello, Welcome to ", " world and ", " page"]

 

'개발 관련 지식 > JS' 카테고리의 다른 글

eslint  (0) 2020.03.07
babel  (0) 2020.03.06
forEach JS  (0) 2020.03.04
filter 함수  (0) 2020.03.03
문자열에서 특정 문자 찾기  (0) 2020.03.01