String ใน JavaScript คืออะไร?
ชนิดข้อมูล (Data Type) สำหรับเก็บข้อความ สร้างได้ 3 วิธี:
const str1 = 'Single quotes'; const str2 = "Double quotes"; const str3 = `Backticks (Template Literal)`;
String Interpolation (Template Literals)
ใช้ Backticks ` ` และ ${expression} แทรกค่าตัวแปรหรือนิพจน์ได้
const name = "John";
console.log(`Hello ${name}!`); // "Hello John!"
การเปรียบเทียบสตริง (Case Insensitive)
ปัญหา: 'kittens' == 'Kittens' → false
วิธีแก้: แปลงให้เป็นตัวพิมพ์ใหญ่หรือเล็กหมดก่อนเปรียบเทียบ
const userInput = 'kittens'; const searchResult = 'Kittens'; console.log(userInput.toUpperCase() === searchResult.toUpperCase()); // true console.log(userInput.toLowerCase() === searchResult.toLowerCase()); // true
สรุป
- ใช้ Backticks สำหรับ Interpolation และ Multiline String
- เปรียบเทียบสตริงควร Normalize Case ก่อน (toLowerCase/toUpperCase)
- มีเมธอดช่วยจัดการสตริงมากมาย:
slice(),replace(),split(),trim()เป็นต้น