카테고리 없음

자바스크립트 split 함수

codinglooking 2026. 4. 27. 16:51

문자열을 분리해서 배열로 반환

split() 함수는 주어진 문자열을 지정한 구분자나 정규 표현식을 기준으로 나누어 새로운 배열로 반환합니다.

이 함수는 규칙에 따라 분리한 문자열을 처리하거나, URL 분석 등에서 유용하게 사용됩니다.

 

이 글은 코딩에브리바디(codingeverybody.kr)의 내용을 참조해 작성했습니다.

 

특징

  • 문자열이 분리되어 배열의 각 요소로 구성됩니다.
  • 새로운 배열을 반환하므로 원본 문자열은 변경되지 않습니다.
/* 특정 구분자를 사용한 문자열 분리 */
const sentence = "자바스크립트는 클라이언트 측 스크립팅 언어입니다.";
const wordsArray = sentence.split(" "); // 공백을 기준으로 문자열을 배열로 나눔

console.log(wordsArray);
// 출력: ["자바스크립트는", "클라이언트", "측", "스크립팅", "언어입니다."]


/* 정규 표현식을 사용한 문자열 분리 */
const str = "This is an example.";
const words = str.split(/\s+/); // 문자열을 공백을 나타내는 정규 표현식(/\s+/)으로 나누어 배열로 변환

console.log(words[0]); // 출력: "This"
console.log(words[1]); // 출력: "is"
console.log(words[2]); // 출력: "an"
console.log(words[3]); // 출력: "example."

/* URL 분석 */
const url = "https://www.example.com/path/to/file.html?param=value";

const parts = url.split("?"); // URL을 구분자로 나누어 배열로 변환

console.log(parts[0]); // 출력: "https://www.example.com/path/to/file.html"
console.log(parts[1]); // 출력: "param=value"

 

구문

str.split()
str.split(separator)
str.split(separator, limit)
  • str: split() 함수를 적용할 원본 문자열입니다.
  • separator: 옵션. 문자열을 나눌 때 사용할 구분자입니다. 문자열 또는 정규 표현식으로 지정할 수 있습니다.
  • limit: 옵션. 문자열을 나눌 때 생성되는 배열의 최대 길이를 제한하는 정수입니다. 생략하면, 구분자를 모두 사용하여 문자열을 나눕니다. 최대 길이를 초과하여 남은 문자열은 반환하는 배열에 포함되지 않습니다.

반환 값

구분자를 기준으로 나뉜 문자열을 요소로 포함하는 배열입니다.

매개변수가 없을 경우

separator를 지정하지 않았을 경우 반환되는 배열은 원본 문자열을 유일한 요소로 가집니다.

const sentence = "반갑습니다. 환영합니다!";
const wordsArray = sentence.split();

console.log(wordsArray);
// 출력: ["반갑습니다. 환영합니다!"]

 

빈 문자열("")을 구분자로 지정했을 경우

separator를 빈 문자열("")로 지정하면 반환되는 배열은 원본 문자의 모든 문자를 요소로 가집니다.

const sentence = "반갑습니다. 환영합니다!";
const wordsArray = sentence.split("");

console.log(wordsArray);
// 출력: ["반", "갑", "습", "니", "다", ".", " ", "환", "영", "합", "니", "다", "!"]

 

separator로 지정한 구분자가 원본 문자열의 처음이나 끝에 있는 경우에 반환되는 배열도 빈 문자열("")로 시작하거나 끝납니다.

const sentence = ",반갑습니다. 환영합니다!";

// 원본 문자열의 처음에 있는 ","를 구분자로 지정합니다.
const wordsArray = sentence.split(",");

// 반환하는 배열의 처음에 빈 문자열("")이 요소로 포함되어 있습니다.
console.log(wordsArray);
// 출력: ["", "반갑습니다. 환영합니다!"]

 

const sentence = "반갑습니다. 환영합니다!,";

// 원본 문자열의 끝에 있는 ","를 구분자로 지정합니다.
const wordsArray = sentence.split(",");

// 반환하는 배열의 끝에 빈 문자열("")이 요소로 포함되어 있습니다.
console.log(wordsArray);
// 출력: ["반갑습니다. 환영합니다!", ""]

 

const sentence = ",반갑습니다. 환영합니다!,";

// 원본 문자열의 처음과 끝에 있는 ","를 구분자로 지정합니다.
const wordsArray = sentence.split(",");

// 반환하는 배열의 처음과 끝에 빈 문자열("")이 요소로 포함되어 있습니다.
console.log(wordsArray);
// 출력: ["", "반갑습니다. 환영합니다!", ""]

 

separator와 원본 문자열이 동일할 경우 빈 문자열("") 두 개를 요소로 가지는 배열이 반환됩니다.

 

const sentence = "반";
const wordsArray = sentence.split("반");

console.log(wordsArray);
// 출력: ["", ""]

 

separator와 원본 문자열이 모두 빈 문자열("")일 경우 빈 배열이 반환됩니다.

const sentence = "";
const wordsArray = sentence.split("");

console.log(wordsArray);
// 출력: []

 

활용 예제

문자열을 단어로 나누기

const str = "This is an example.";
const words = str.split(" ");

console.log(words);
// 출력: ["This", "is", "an", "example."]

 

문자열 파싱하기

const time = "02:30:45";
const timeParts = time.split(":");
const hours = timeParts[0];

console.log("Hours:", hours);
// 출력: "Hours: 02"

 

파일 경로에서 파일 이름 추출하기

const filePath = "/path/to/file.txt";

/* "/"로 나누고 배열의 마지막 요소를 pop() 함수로 반환 */
const fileName = filePath.split('/').pop();

console.log(fileName);
// 출력: "file.txt"

 

이메일 주소에서 도메인 추출하기

const email = "user@example.com";
const parts = email.split("@");

const domain = parts[1];

console.log(domain);
// 출력 "example.com"

 

또 다른 출처 정보

https://coding.courses/javascript-split-function/

 

JavaScript split() Function – Splitting a String and Returning an Array - codingCourses

The split() function splits a given string based on a specified delimiter or a regular expression and returns a new array.

coding.courses

 

https://codingeverybody.jp/javascript-split-function/

 

JavaScript split()関数:文字列を分割して配列として返す - codingEverybody

split()関数は、指定された文字列を区切り文字や正規表現を基準に分割し、新しい配列として返します。

codingeverybody.jp