ใช้ split() แยกสตริงด้วยตัวคั่น แล้ว filter() กรองค่าว่างออก
ตัวอย่างโค้ด
var sentence = "-My-Name-is-John-Smith-I-live-in-US";
console.log("The value=" + sentence);
var result = sentence.split('-').filter(value => value);
console.log("After split()=");
console.log(result);
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo63.js)
ผลลัพธ์
The value=-My-Name-is-John-Smith-I-live-in-US
After split()= [ 'My', 'Name', 'is', 'John', 'Smith', 'I', 'live', 'in', 'US' ]