JavaScript สตริงย่อย ()
ตัวอย่าง
แยกสตริงย่อยออกจากข้อความ:
let text = "Hello world!";
let result = text.substr(1, 4);"
เริ่มต้นที่ตำแหน่ง 2:
let result = text.substr(2);
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
วิธี การsubstr()
แยกส่วนของสตริง
วิธี การsubstr()
เริ่มต้นที่ตำแหน่งที่ระบุ และส่งกลับจำนวนอักขระที่ระบุ
วิธี การsubstr()
นี้จะไม่เปลี่ยนสตริงเดิม
หากต้องการแยกอักขระออกจากส่วนท้ายของสตริง ให้ใช้ตำแหน่งเริ่มต้นเชิงลบ
ไวยากรณ์
string.substr(start, length)
พารามิเตอร์
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
สตริง | สตริงที่มีส่วนที่แยกออกมา ถ้าความยาว เป็น 0 หรือค่าลบ สตริงว่างจะถูกส่งกลับ |
ตัวอย่างเพิ่มเติม
ครั้งแรกเท่านั้น:
let result = text.substr(0, 1);
สุดท้ายเท่านั้น:
let result = text.substr(text.length-1, 1);
6 คนสุดท้าย:
let result = text.substr(-5, 5);
รองรับเบราว์เซอร์
substr()
เป็นคุณลักษณะ ECMAScript1 (ES1)
ES1 (JavaScript 1997) ได้รับการสนับสนุนอย่างสมบูรณ์ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |