[javascript] 문자열 분리하기
자바스크립트에서는 문자열을 분리하는 여러 가지 방법이 있습니다. 이 글에서는 가장 자주 사용되는 방법을 알아보겠습니다.
1. split() 메서드
split() 메서드는 문자열을 지정한 구분자를 기준으로 분리하여 배열로 반환합니다. 예를 들어, 아래와 같은 문자열에서 ,
로 구분된 각 단어를 분리해보겠습니다.
const string = "apple, banana, orange";
const words = string.split(", ");
console.log(words); // ["apple", "banana", "orange"]
2. match() 메서드
match() 메서드는 정규 표현식을 사용하여 문자열을 분리하는 방법입니다. 예를 들어, 숫자와 알파벳을 분리해보겠습니다.
const string = "123abc456def";
const regex = /[0-9]|[a-z]+/gi;
const words = string.match(regex);
console.log(words); // ["123", "abc", "456", "def"]
3. substring() 메서드
substring() 메서드는 지정한 인덱스 사이의 문자열을 가져오는 방법입니다. 예를 들어, 처음부터 3번째 문자까지의 문자열을 분리해보겠습니다.
const string = "Hello, world!";
const substring = string.substring(0, 3);
console.log(substring); // "Hel"
4. slice() 메서드
slice() 메서드는 지정한 인덱스 사이의 문자열을 가져오는 방법입니다. substring()과는 달리 음수 인덱스도 사용할 수 있습니다. 예를 들어, 마지막 6개의 문자열을 분리해보겠습니다.
const string = "Hello, world!";
const substring = string.slice(-6);
console.log(substring); // "world!"
참고 자료
- MDN 문서 - String.prototype.split()
- MDN 문서 - String.prototype.match()
- MDN 문서 - String.prototype.substring()
- MDN 문서 - String.prototype.slice()
위에서 소개한 방법들을 사용하여 문자열을 분리해보세요!