문자열을 자르는 방법

Hyunwoo Seo·2022년 9월 13일
0

JavaScript

목록 보기
7/31
post-thumbnail

자바스크립트에서는 문자열을 자르는 방법으로 split, substring, substr 함수를 제공한다.


split 정의와 사용법

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

반환

: split은 문자열을 separator를 기준으로 limit 만큼의 크기를 가진 새로운 문자 배열을 반환한다.

separator (option)

: 구분자는 문자열을 나눌 때 기준이 되는 값 으로 문자(character)이나 정규표현식을 사용할 수 있다. 값을 정하지 않으면 str과 동일한 값을 가진 문자 배열을 반환한다.

limit (option)

: 반환하는 문자 배열 의 최대 크기다. 값을 정하지 않으면 문자 배열의 크기는 제한되지 않는다.(나누어진 배열요소들을 모두 반환한다)

예제 코드

const text = 'Hello, world!';

const splitResult = text.split(',');
// ["Hello", " world!"]

const splitResultByLimit0 = text.split(',', 0);
// []

const splitResultByLimit1 = text.split(',', 1);
// ["Hello"]

const splitResultByLimit2 = text.split(',', 2);
// ["Hello", " world!"]

substring 정의와 사용법

str.substring(indexStart[, indexEnd])

반환

: substring는 기존 문자열의 indexStart 위치에서 indexEnd 까지 잘라 부분으로 문자열을 반환한다.

indexStart (required)

: 자르는 문자의 시작 위치 값.

indexEnd (option)

: 자르는 문자의 마지막 위치 값. 생략이 가능하며 생략을 하는 경우 대상 문자열의 마지막 위치 값을 설정한다.

예제 코드

const text = 'Hello, world!';

console.log(text.substring(0, 1));
// H
console.log(text.substring(1, 0));
// H

console.log(text.substring(0, 5));
// Hello

console.log(text.substring(5));
// , world!

console.log(text.substring(0));
// Hello, world!

substr 정의와 사용법

str.substr(start[, length])

반환

: substr은 기존 문자열의 start 위치에서 length 만큼 문자열을 반환한다.

start (required)

: 자르는 문자의 시작 위치 값.

length (option)

: 자르는 문자열의 길이 값. 생략이 가능하며 생략을 하는 경우 문자열의 start 위치부터 문자열의 끝까지 추출하여 반환한다.

substr은 ECMAScript 1, 2에 포함되지 않으며 3의 부록에 정의되어 있는 사양(spec)으로 사용이 권장되지 않는다.

예제 코드

const text = 'Hello, world!';

console.log(text.substr(0, 1));
// H
console.log(text.substr(1, 0));
// 

console.log(text.substr(0, 5));
// Hello

console.log(text.substr(5));
// , world!

console.log(text.substr(0));
// Hello, world!

split(), substring(), substr()의 차이 알아보기

const text = 'Hello, world!';

console.log(text.split(','));
// ["Hello", " world!"]

console.log(text.substring(5, 6));
// ,

console.log(text.substr(5, 6));
// , worl

0개의 댓글