ใช้ Regex /\s/g กับ replace() เพื่อลบ Whitespace ทั้งหมด (Space, Tab, Newline, ฯลฯ) ออกจากสตริง
ตัวอย่าง
<html>
<head>
<script>
var str = "Welcome to Tutorialspoint";
document.write(str);
// ลบ whitespace ทั้งหมด
document.write("<br>" + str.replace(/\s/g, ''));
</script>
</head>
<body>
</body>
</html>
ผลลัพธ์
Welcome to Tutorialspoint WelcometoTutorialspoint
รายละเอียด \s
| Escape Sequence | ความหมาย |
|---|---|
\s | Whitespace ทุกชนิด: Space, Tab (\t), Newline (\n), Carriage Return (\r), Form Feed (\f), Vertical Tab (\v) |
\S | Non-whitespace (ตรงข้าม) |
ตัวอย่างเพิ่มเติม
var str = " Hello \t World \n "; // ลบ whitespace ทั้งหมด str.replace(/\s/g, ''); // "HelloWorld" // ลบเฉพาะ Space (ไม่รวม Tab, Newline) str.replace(/ /g, ''); // "Hello\tWorld\n" // Trim (ลบหน้า/หลัง) - ใช้เมธอด內建 trim() str.trim(); // "Hello \t World" // แทนที่ whitespace หลายตัวเป็น Space เดียว str.replace(/\s+/g, ' '); // " Hello World "
แนะนำ: ใช้ str.trim() สำหรับลบช่องว่างหน้า/หลัง ใช้ str.replace(/\s+/g, ' ') สำหรับ Normalize whitespace ใช้ str.replace(/\s/g, '') สำหรับลบทั้งหมด