สมมติว่าต่อไปนี้คือสตริงของเราที่มีคอมมาและช่องว่าง:
var sentences = " John , David , Bob , Mike, Carol ";
เพื่อแบ่งประโยคด้วยคอมมา ใช้ split() สำหรับลบช่องว่างรอบข้าง ใช้ trim()
ตัวอย่าง
var sentences = " John , David , Bob , Mike, Carol ";
console.log("The value=" + sentences);
var result = sentences.split(",").map(function (value) {
return value.trim();
});
console.log("After modifying the value=")
console.log(result);
เพื่อรันโปรแกรมข้างต้น ใช้คำสั่งต่อไปนี้:
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo235.js
ผลลัพธ์
ผลลัพธ์มีดังนี้:
PS C:\Users\Amit\javascript-code> node demo235.js The value= John , David , Bob , Mike, Carol After modifying the value= [ 'John', 'David', 'Bob', 'Mike', 'Carol' ]