สมมติสตริงของเราที่มีช่องว่างคือ
var fullName=" John Smith ";
ใช้ replace() และตั้งค่า Regex เพื่อลบช่องว่าง
ตัวอย่าง
function removeSpacesAtTheBeginningAndTheEnd(name) { return name.toString().replace(/^\s+|\s+$/g,''); } var fullName=" John Smith "; var valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName) console.log(valueAfterRemovingSpace);
เพื่อรันโปรแกรมด้านบน คุณต้องใช้คำสั่งต่อไปนี้
node fileName.js.
ที่นี่ชื่อไฟล์ของผมคือ demo208.js
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
PS C:\Users\Amit\javascript-code> node demo208.js John Smith