Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบช่องว่าง (Whitespace) ทั้งหมดใน String ด้วย JavaScript

เพื่อลบช่องว่างทั้งหมดใน 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.