เรียนรู้แทนที่ white space ใน strings ด้วย Regex (Regular Expressions) — tool หา patterns ใน text
Regex (RegEx/RegExp) performant tool สำหรับ strings ใช้บ่อย:
- Text validation
- Text searching
วันนี้เรียนจากตัวอย่าง regex replace white space ทั้งหมดในบรรทัดด้วย nothing — แต่用ได้กับ character อื่นๆ
White space = character ทุกช่องว่างระหว่างคำในประโยคนี้ = 1 white space character
ประโยคนี้มี 6 white space characters
Regex meta-character \s หา single white space character (รวม newline, tabs, Unicode)
const sentence = "This sentence has 6 white space characters.";
console.log(sentence.replace(/\s/g, "")); // Thissentencehas6whitespacecharacters.
Code explanation:
- Attach
replace()กับsentencevariable - Argument
\smeta character หา whitespace ใส่/หน้า \ เพื่อ unescape →/\s/ - Global
gflag = หา ทั้งหมด whitespace ไม่ใส่ g = แทนที่แค่ตัวแรก (ระหว่าง This sentence) - Replace ด้วย empty string
""→ ลบ whitespace ทำให้คำติดกัน
Note: sentence variable ไม่เปลี่ยน แค่ log ผลลัพธ์
อยากเปลี่ยนค่า sentence ต้อง assign variable ใหม่:
const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "");
console.log(sentenceRemoveWhiteSpace); // Thissentencehas6whitespacecharacters.
ตรวจสอบจำนวน whitespace ด้วย match():
console.log(sentence.match(/\s/g).length); // 6