/* 특정 구분자를 사용한 문자열 분리 */
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(separator, limit)
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);
// 출력: ["", "반갑습니다. 환영합니다!"]
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);
// 출력: ["", ""]
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"
const url = "https://www.example.com/path/to/file.html?param=value";
const parts = url.split("://");

const protocol = parts[0];

console.log(protocol);
// 출력 "https"
문자열 split() 함수의 브라우저 호환성
메서드
데스크탑 Chrome
Chrome
데스크탑데스크탑 Edge
Edge
데스크탑 Firefox
Firefox
Safari
Safari
split() 1 12 1 1

caniuse.com에서 더 자세한 정보를 확인해 보세요.