😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。
定義と使い方
split()関数は、指定された 区切り文字や正規表現を基準に文字列を分割し、新しい配列として返します。この関数は、規則に従って分割した文字列を処理したり、URLの解析などで便利に使用されます。
特徴
- 文字列が分離され、配列の各要素として構成されます。
- 新しい配列を返却するため、元の文字列は変更されません。
基本例
/* 特定の区切り文字を使用した文字列の分割 */
const sentence = "JavaScriptはクライアントサイドのスクリプト言語です。";
const wordsArray = sentence.split(" "); // 空白を基準に文字列を配列に分割
console.log(wordsArray);
// 出力: ["JavaScriptは", "クライアントサイドの", "スクリプト言語です。"]
/* 正規表現を使用した文字列の分割 */
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]); // 出ly: "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)
活用例
# 文字列を単語に分割する
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"
参考資料