เพื่อลบช่องว่างทั้งหมดใน string ด้วย JavaScript ใช้ RegEx:
const sentence = "This sentence has 6 white space characters.";
console.log(sentence.replace(/\s/g, ""));
// "Thissentencehas6whitespacecharacters."
ตัวอย่างข้างบนแค่ log ผลลัพธ์ ไม่ได้บันทึกการเปลี่ยนแปลง
หากต้องการลบ whitespace อย่างถาวร ต้องสร้างตัวแปรใหม่และกำหนดค่า:
// Sentence with whitespaces
const sentence = "This sentence has 6 white space characters.";
// Sentence without whitespace
const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "");
console.log(sentenceRemoveWhiteSpace);
// Thissentencehas6whitespacecharacters.