สมมติว่ามีสตริงที่มีเครื่องหมายคอลอนสองตัว:
var values = "This is:the first program in JavaScript:After that I will do Data Structure program";
ต้องการดึงข้อความระหว่างคอลอนทั้งสอง ใช้ split()
ตัวอย่างโค้ด
var values = "This is:the first program in JavaScript:After that I will do Data Structure program";
var result = [];
result = values.split(":");
console.log(result[1]);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo273.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo273.js the first program in JavaScript
คำอธิบาย: split(":") แยกสตริงเป็นอาร์เรย์ 3 ส่วน ดัชนี [1] คือส่วนกลางระหว่างคอลอนทั้งสอง
ขยายความสามารถ: หากมีคอลอนมากกว่า 2 ตัว และต้องการระหว่างคู่ที่ n ใช้ split() แล้วเลือกดัชนีที่ต้องการ หรือใช้ Regex