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

การลบช่องว่างออกจากสตริงใน JavaScript

ภาพรวม

บทความนี้แสดงวิธีเขียนฟังก์ชัน JavaScript เพื่อลบช่องว่าง (whitespace) ทั้งหมดออกจากสตริง โดยคืนค่าสตริงใหม่ที่ไม่มีช่องว่าง

ตัวอย่าง

const str = "This is an example string from which all whitespaces will be removed";

const removeWhitespaces = (str) => {
  let newStr = '';
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== ' ') {
      newStr += str[i];
    }
  }
  return newStr;
};

console.log(removeWhitespaces(str));

ผลลัพธ์

Thisisanexamplestringfromwhichallwhitespaceswillberemoved

วิธีการที่ทันสมัยกว่า (ES6+)

ใน JavaScript สมัยใหม่ สามารถใช้เมธอด replaceAll() หรือ split().join() ได้ง่ายกว่า:

// วิธีที่ 1: ใช้ replaceAll (รองรับในเบราว์เซอร์สมัยใหม่)
const removeSpaces1 = str => str.replaceAll(' ', '');

// วิธีที่ 2: ใช้ split และ join
const removeSpaces2 = str => str.split(' ').join('');

// วิธีที่ 3: ใช้ Regular Expression (ลบ whitespace ทุกประเภท: space, tab, newline)
const removeAllWhitespace = str => str.replace(/\s+/g, '');

เปรียบเทียบประสิทธิภาพ

  • Loop แบบเดิม: เข้าใจง่าย ใช้ได้ทุกสภาพแวดล้อม แต่ช้ากว่า
  • replaceAll: อ่านง่าย เร็ว แต่ต้องการสภาพแวดล้อม ES2021+
  • Regex: ครอบคลุม whitespace ทุกชนิด เหมาะสำหรับการทำความสะอาดข้อมูลจริง