JavaScript
String Methods
split
เรียนรู้ split() — method แยก string เป็น array ด้วย separator ตั้งแต่การทำงานพื้นฐานด้วย space และ comma, พฤติกรรมของ separator แบบต่าง ๆ (เจอ/ไม่เจอ/empty string), limit parameter สำหรับจำกัดจำนวน element, การใช้จริงกับ CSV/URL/log/file, ไปจนถึงข้อควรระวังและ common mistakes ผ่าน Lab 5 ข้อ
`split()` คืออะไร — แยก string เป็น array ด้วย separator
`split()` เป็น method บน string ใช้แยก string ออกเป็น array ของ substring — โดยใช้ **separator** (ตัวคั่น) เป็นตัวกำหนดจุดตัด — คืนค่าเป็น array โดยไม่เปลี่ยน string ต้นฉบับ สิ่งที่ต้องรู้: • `split(separator)` — ตัด string ทุกจุดที่เจอ separator ได้ array ของส่วนที่เหลือ • `split(separator, limit)` — ระบุจำนวนสูงสุดของ element ใน array ผลลัพธ์ (optional) • separator เป็น string ธรรมดา เช่น `","`, `" "`, `"-"` — ไม่ใช่ regex ในตัวอย่างพื้นฐาน • คืนค่าเป็น array — string ต้นฉบับไม่เปลี่ยน (immutable) • ถ้าไม่เจอ separator เลย — ได้ array ที่มี string ต้นฉบับเป็น element เดียว
const sentence = "hello world javascript";
// split(" ") — ตัดทุกช่องว่าง ได้ array ของคำ
const words = sentence.split(" ");
console.log(words); // ["hello", "world", "javascript"]
console.log(words.length); // 3
// string ต้นฉบับไม่เปลี่ยน
console.log(sentence); // "hello world javascript"const csv = "apple,banana,orange,grape";
// split(",") — ตัดทุก comma ได้ array ของผลไม้
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "orange", "grape"]
console.log(fruits.length); // 4
// === เข้าถึงแต่ละ element เหมือน array ปกติ
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "orange"- `split(separator)` — ตัด string ทุกจุดที่เจอ separator ได้ array ของ substring
- คืนค่าเป็น array — string ต้นฉบับไม่เปลี่ยน (immutable)
- separator ต้องเป็น string — `","` `" "` `"-"` `"|"` ฯลฯ
- ถ้าไม่เจอ separator — ได้ array ที่มี string เดิมเป็น element เดียว
- ผลลัพธ์เป็น array — ใช้ index, length, และ method ของ array ได้ทันที
separator — ตัวคั่นกำหนดจุดตัด และพฤติกรรมเมื่อไม่เจอ / เป็น empty string
separator คือหัวใจของ `split()` — ตัวมันกำหนดว่าจะตัด string ที่ตำแหน่งไหน และผลลัพธ์จะหน้าตาอย่างไร พฤติกรรมสำคัญ 3 แบบที่ควรรู้: • **เจอ separator** → ตัดตรงนั้น — ส่วนที่อยู่ระหว่าง separator จะกลายเป็น element ใน array • **ไม่เจอ separator** → ไม่มีการตัด — ได้ array ที่มี string ต้นฉบับเป็น element เดียว • **separator เป็น empty string `""`** → ตัดทุกตัวอักษร — ได้ array ของแต่ละ character
| กรณี | Separator | Input | ผลลัพธ์ |
|---|---|---|---|
| เจอ separator | `,` | `"a,b,c"` | `["a", "b", "c"]` |
| ไม่เจอ separator | `,` | `"hello"` | `["hello"]` (element เดียว) |
| empty string `""` | `""` | `"abc"` | `["a", "b", "c"]` (แยกทีละตัว) |
| space | `" "` | `"hello world"` | `["hello", "world"]` |
| dash | `"-"` | `"2024-01-15"` | `["2024", "01", "15"]` |
const text = "hello world javascript";
// === เจอ separator — ตัดทุก space
console.log(text.split(" "));
// ["hello", "world", "javascript"]
// === ไม่เจอ separator — ได้ array element เดียว
console.log(text.split(","));
// ["hello world javascript"]
// === empty string "" — แยกทีละตัวอักษร
console.log(text.split(""));
// ["h","e","l","l","o"," ","w","o","r","l","d"," ","j","a","v","a","s","c","r","i","p","t"]
// === ใช้จริง — กลับ string ด้วย split + reverse + join
const reversed = text.split("").reverse().join("");
console.log(reversed); // "tpircsavaj dlrow olleh"- **เจอ separator → ตัด** — `"a-b-c".split("-")` → `["a","b","c"]`
- **ไม่เจอ separator → ไม่ตัด** — `"hello".split(",")` → `["hello"]` (ยังเป็น array นะ!)
- **empty string `""` → แยกทีละตัว** — `"abc".split("")` → `["a","b","c"]` ใช้บ่อยกับ reverse string
- **split คืน array เสมอ** — แม้จะไม่เจอ separator ก็ตาม
limit parameter — จำกัดจำนวนส่วนที่ได้จาก `split()`
`split()` รับ parameter ตัวที่สอง (optional) คือ **limit** — ตัวเลขที่กำหนดจำนวน element สูงสุดใน array ผลลัพธ์ พอถึง limit แล้ว — `split()` จะหยุดตัดและเอาส่วนที่เหลือทั้งหมดใส่ใน element สุดท้าย ใช้ limit เมื่อ: • อยากได้แค่ N ส่วนแรกของ string — ไม่สนใจส่วนที่เหลือ • ข้อมูลมี delimiter เยอะแต่เราอยากได้แค่ 2-3 ฟิลด์แรก • ป้องกัน array ผลลัพธ์ยาวเกินไป
const data = "a-b-c-d-e";
// === ไม่มี limit — ได้ทุกส่วน
console.log(data.split("-"));
// ["a", "b", "c", "d", "e"] — 5 elements
// === limit = 3 — ได้แค่ 3 elements แรก
console.log(data.split("-", 3));
// ["a", "b", "c-d-e"] — element สุดท้ายรวมส่วนที่เหลือไว้
// === limit = 2 — ได้แค่ 2 elements
console.log(data.split("-", 2));
// ["a", "b-c-d-e"]
// === limit = 1 — ไม่ตัดเลย เหมือนไม่เจอ separator
console.log(data.split("-", 1));
// ["a-b-c-d-e"]
// === ใช้จริง — ดึงแค่ชื่อกับนามสกุลจาก "John,Doe,25,Bangkok"
const record = "John,Doe,25,Bangkok";
const [first, last] = record.split(",", 2);
console.log(first); // "John"
console.log(last); // "Doe"// === URL path — อยากได้แค่ 2 ส่วนแรก
const path = "docs/javascript/string-methods/split";
const parts = path.split("/", 2);
console.log(parts); // ["docs", "javascript"]
// === log message — อยากแยกแค่ level กับ message
const log = "ERROR:2024-01-15:Connection failed:timeout=30s";
const [level, ...message] = log.split(":", 2);
console.log(level); // "ERROR"
console.log(message); // "2024-01-15:Connection failed:timeout=30s"- **`split(sep, limit)` — limit คือจำนวน element สูงสุด** — ไม่ใช่จำนวนครั้งที่ตัด
- **limit=2 → ได้ 2 elements** — element สุดท้ายรวมส่วนที่เหลือทั้งหมด
- **limit=1 → ไม่ตัดเลย** — ได้ array element เดียวที่มี string ทั้งหมด
- **limit ไม่ระบุ (หรือมากเกิน) → ตัดทุกจุด** — ได้ array เต็ม
ใช้ `split()` ในสถานการณ์จริง — ตั้งแต่ CSV ยัน URL parsing
`split()` เป็นหนึ่งใน method ที่ใช้บ่อยที่สุดในงานจริง — เพราะข้อมูลในชีวิตจริงมักมาในรูปแบบ string ที่มีตัวคั่น เช่น CSV, log files, URL, ชื่อไฟล์, หรือ output จาก API ความสามารถของ `split()` รวมกับการ destructuring และ method ของ array ทำให้เราจัดการข้อมูล string ได้ทรงพลังมาก
// === ข้อมูลผู้ใช้แบบ CSV — "ชื่อ,อายุ,เมือง"
const userData = "Mali,28,Chiang Mai";
// split + destructuring — ดึงทีละฟิลด์
const [name, age, city] = userData.split(",");
console.log(name); // "Mali"
console.log(age); // "28"
console.log(city); // "Chiang Mai"
// === ใช้ต่อ — แสดง profile
console.log(name + " อายุ " + age + " ปี อยู่ " + city);
// "Mali อายุ 28 ปี อยู่ Chiang Mai"
// === ระวัง — age เป็น string ต้องแปลงเป็น number ถ้าจะคำนวณ
const ageNum = Number(age);
console.log("อีก 10 ปีอายุ:", ageNum + 10); // 38// === ดึงนามสกุลไฟล์ — split(".") แล้วเอาตัวสุดท้าย
const filename = "photo.jpg";
const parts = filename.split(".");
console.log(parts[parts.length - 1]); // "jpg"
// === แยก URL path
const url = "https://example.com/docs/js/split";
const segments = url.split("/");
console.log(segments[segments.length - 1]); // "split"
// === แยก log — เอา timestamp กับ message
const log = "2024-01-15 14:30:22 | User login | success";
const [timestamp, action, status] = log.split(" | ");
console.log("เวลา:", timestamp); // "เวลา: 2024-01-15 14:30:22"
console.log("action:", action); // "action: User login"
console.log("status:", status); // "status: success"
// === แยก key=value — ใช้ split "="
const config = "theme=dark";
const [key, value] = config.split("=");
console.log(key + " → " + value); // "theme → dark"- **parse CSV** — `row.split(",")` + destructuring หรือ loop
- **ดึงนามสกุลไฟล์** — `filename.split(".").pop()`
- **แยก URL path** — `url.split("/")` แล้วเข้าถึง segment ที่ต้องการ
- **แยก log message** — `log.split(" | ")` เมื่อมี delimiter ที่ชัดเจน
- **แยก key=value** — `pair.split("=")` สำหรับ config, query string พื้นฐาน
- **ประกอบกับ join()** — split → process → join = pattern จัดการ string ที่พบบ่อย
ข้อควรระวังและ common mistakes — `split()` ไม่ได้ง่ายอย่างที่คิด
ถึงแม้ `split()` จะใช้ง่าย — แต่มีจุดที่พลาดบ่อย 5 จุดที่ควรระวัง: 1. **split คืน array เสมอ** — แม้ input จะเป็น `""` (empty string) ก็ได้ `[""]` ไม่ใช่ `[]` 2. **separator ที่ติดกัน** — `"a,,b"` แยกด้วย `","` จะได้ `["a", "", "b"]` — มี empty string ตรงกลาง 3. **ไม่เปลี่ยน string ต้นฉบับ** — อย่าลืมรับค่าที่คืนมา `const result = str.split(",")` ไม่ใช่ `str.split(",")` แล้วทิ้ง 4. **separator ต้องเป็น string** — ถ้าจะแยกด้วยหลายตัวคั่นพร้อมกันต้องใช้ regex 5. **split + join ≠ revert** — `"a-b-c".split("-").join("-")` ได้ `"a-b-c"` กลับมา แต่ `"a-b-c".split("-").join(",")` ได้ `"a,b,c"`
// === Mistake 1: empty string → split("") ไม่ได้ []
console.log("".split(",")); // [""] — ไม่ใช่ []!
console.log("".split(",").length); // 1 — ไม่ใช่ 0
// === Mistake 2: separator ติดกัน → empty string ใน array
console.log("a,,b".split(","));
// ["a", "", "b"] — empty string ตรงกลาง ไม่ใช่ ["a", "b"]
// === Mistake 3: ไม่รับค่า — str.split() ไม่เปลี่ยน str
let str = "hello world";
str.split(" "); // ✗ — เรียกแล้วทิ้ง!
console.log(str); // "hello world" — ไม่เปลี่ยน
// ต้อง: str = str.split(" "); // ถึงจะได้ค่าที่ split แล้ว
// === Mistake 4: ใช้ separator ผิด — ข้อมูลมี space แต่ใช้ comma
console.log("hello world".split(","));
// ["hello world"] — element เดียว เพราะไม่เจอ comma
// === Mistake 5: split + join เปลี่ยน delimiter
console.log("2024-01-15".split("-").join("/"));
// "2024/01/15" — แปลงจาก dash เป็น slash- **`"".split(",")` → `[""]` ไม่ใช่ `[]`** — empty string แยกแล้วได้ array ที่มี empty string element เดียว
- **separator ติดกัน → empty element** — `"a,,b".split(",")` มี `""` ตรงกลาง
- **อย่าลืมรับค่าที่คืน** — `split()` ไม่ mutate ต้นฉบับ ต้อง `str = str.split()` หรือใช้ตัวแปรใหม่
- **separator ผิด → ไม่ตัด** — เช็กเสมอว่า separator ตรงกับข้อมูลจริง เช่น space vs comma