เมธอด JavaScript substring() ดึงช่วงตัวอักษรระหว่าง 2 index positions สามารถดึงจนถึงท้าย string ได้โดยไม่ระบุ end index
วิธีใช้ JavaScript substring()
substring() ดึงส่วนของ string ระหว่าง 2 index values โดยไม่ระบุ end index จะดึงทุกตัวอักษรหลัง start index
รับ 2 arguments:
- ตำแหน่งเริ่มต้น (start) - required
- ตำแหน่งสิ้นสุด (end) - optional
Syntax:
"test".substring(start, end);
substring() ต่อท้าย string เริ่มต้น ต้องมี start parameter อย่างน้อย
ตัวอย่างการใช้งาน
1. ดึงตัวอักษรจนท้าย String
const catName = "Pickles"; const newCatName = catName.substring(2); console.log(newCatName); // "ckles"
ระบุแค่ start=2 คืนค่าตัวอักษรทุกตัวหลัง index 2
2. ดึงตัวอักษรในช่วง (Range)
const catName = "Pickles"; const newCatName = catName.substring(0, 3); console.log(newCatName); // "Pic"
ดึง index 0, 1, 2 (end ไม่รวม index 3) จำไว้: string index เริ่มจาก 0
3. ดึงตัวอักษรตัวสุดท้าย
substring() ไม่รองรับ negative index ใช้ length property แทน:
const catName = "Pickles"; const newCatName = catName.substring(catName.length - 1, catName.length); console.log(newCatName); // "s"
catName.length = 7 ดึง index 6 ถึง 7 ได้ตัวสุดท้าย
สรุป
substring() คืนค่าตัวอักษรระหว่าง 2 index values ใน array หากไม่ระบุ end index จะคืนค่าทุกตัวหลัง start index ใช้แยก string หลายส่วน เมื่อต้องการข้อมูลเฉพาะจาก string