หากต้องการลบช่องว่างเพิ่มเติม คุณต้องใช้ trim() ร่วมกับนิพจน์ทั่วไป ต่อไปนี้เป็นสตริงของเราที่มีช่องว่างก่อนใช้ trim() -
var sentence="My name is John Smith ";
ตอนนี้ เราจะลบช่องว่างพิเศษตามโค้ดด้านล่าง -
ตัวอย่าง
var sentence="My name is John Smith ";
console.log("The actual value=");
console.log(sentence);
var originalSentence = sentence.replace(/\s+/g,'').trim();
var afterRemovingTheSpace=originalSentence.trim();
console.log("After removing the spaces=");
console.log(afterRemovingTheSpace); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo90.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
PS C:\Users\Amit\JavaScript-code> node demo90.js The actual value= My name is John Smith After removing the spaces= MynameisJohnSmith