ข้ามไปยังเนื้อหาหลัก
คู่มือระบบ เนื้อหาผ่านการตรวจสอบแล้ว

การใช้งาน Template Literals

บทความนี้แนะนำ Template Literals ใน JavaScript ซึ่งเป็นวิธีการสร้าง string ที่ยืดหยุ่นกว่าเดิมโดยใช้ backtick (`) แทน quotes ธรรมดา ทำให้สามารถแทรกตัวแปรและ exp...

การใช้งาน Template Literals ใน JavaScript

ในบทความที่แล้ว เราได้เรียนรู้เรื่องตัวแปร const และ let ไปแล้ว ในบทความนี้ เราจะมาทำความรู้จักกับ Template Literals ซึ่งเป็นอีกหนึ่งฟีเจอร์ที่สำคัญของ JavaScript ที่ช่วยให้การจัดการ string เป็นเรื่องง่ายและสะดวกมากยิ่งขึ้น

Template Literals คืออะไร?

Template Literals คือวิธีการสร้าง string ใน JavaScript ที่มีความยืดหยุ่นและอ่านง่ายกว่าการใช้ single quote (') หรือ double quote (") แบบเดิมๆ จุดเด่นของ Template Literals คือการใช้ backtick (`) แทน quotes และสามารถแทรกตัวแปรหรือ expression ลงใน string ได้โดยตรง

ทำไมต้องใช้ Template Literals?

ก่อนที่จะมี Template Literals การสร้าง string ที่มีการรวมค่าของตัวแปรหรือการสร้าง string ที่มีหลายบรรทัดอาจจะยุ่งยากและต้องใช้ concatenation (การเชื่อมต่อ string) ซึ่งทำให้โค้ดอ่านยากและมีโอกาสผิดพลาดได้ง่าย

Template Literals ช่วยแก้ปัญหาเหล่านี้ได้ด้วยคุณสมบัติดังนี้:

  • การแทรกตัวแปร (String Interpolation): สามารถแทรกตัวแปรหรือ expression ลงใน string ได้โดยใช้ ${}
  • Multiline Strings: สามารถสร้าง string ที่มีหลายบรรทัดได้โดยไม่ต้องใช้ escape character (\n)
  • Expression Evaluation: สามารถใส่ JavaScript expression ลงใน ${} และ JavaScript จะประเมินผลลัพธ์ของ expression นั้น

การใช้งาน Backtick (`)

Template Literals ถูกสร้างขึ้นโดยการครอบข้อความด้วย backtick (`) ซึ่งเป็น character ที่อยู่บนปุ่ม tilde (~) บนคีย์บอร์ด (โดยปกติจะอยู่ทางซ้ายของเลข 1)

const greeting = `สวัสดี`;
console.log(greeting); // Output: สวัสดี

การแทรกตัวแปรด้วย ${}

คุณสมบัติที่สำคัญที่สุดของ Template Literals คือการแทรกตัวแปรลงใน string ได้โดยใช้ ${} ภายใน ${} คุณสามารถใส่ชื่อตัวแปรหรือ JavaScript expression ใดๆ ก็ได้

const name = "John";
const age = 30;

const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // Output: My name is John and I am 30 years old.

จากตัวอย่างข้างต้น เราได้สร้างตัวแปร name และ age จากนั้นเราได้ใช้ Template Literals เพื่อสร้าง string message โดยแทรกค่าของตัวแปรทั้งสองลงไปโดยใช้ ${name} และ ${age}

เราสามารถใช้ expression ที่ซับซ้อนกว่านี้ได้เช่นกัน:

const price = 10;
const quantity = 5;

const total = `The total cost is ${price * quantity} dollars.`;
console.log(total); // Output: The total cost is 50 dollars.

ในตัวอย่างนี้ เราได้ใช้ expression price * quantity ภายใน ${} เพื่อคำนวณราคารวม

การสร้าง Multiline String

Template Literals ทำให้การสร้าง string ที่มีหลายบรรทัดเป็นเรื่องง่าย เพียงแค่ขึ้นบรรทัดใหม่ภายใน backtick (`) โดยไม่ต้องใช้ escape character (\n)

const multilineString = `This is a
string that spans
multiple lines.`;

console.log(multilineString);
// Output:
// This is a
// string that spans
// multiple lines.

เมื่อเปรียบเทียบกับการสร้าง multiline string ด้วย single quote หรือ double quote คุณจะต้องใช้ concatenation และ escape character (\n) ซึ่งทำให้โค้ดอ่านยากขึ้น:

const oldMultilineString = "This is a\n" +
                           "string that spans\n" +
                           "multiple lines.";

console.log(oldMultilineString);
// Output:
// This is a
// string that spans
// multiple lines.

จากตัวอย่างข้างต้น จะเห็นได้ว่าการใช้ Template Literals ทำให้โค้ดอ่านง่ายและ maintain ได้ง่ายกว่า

ตัวอย่างการใช้งานจริง

Template Literals ถูกนำไปใช้ในหลากหลายสถานการณ์ ตัวอย่างเช่น การสร้าง HTML string แบบ dynamic:

const product = {
  name: "Laptop",
  price: 1200,
  description: "A powerful laptop for all your needs."
};

const productHTML = `
  <div class="product">
    <h2>${product.name}</h2>
    <p>Price: $${product.price}</p>
    <p>Description: ${product.description}</p>
  </div>
`;

console.log(productHTML);
// Output:
// <div class="product">
//   <h2>Laptop</h2>
//   <p>Price: $1200</p>
//   <p>Description: A powerful laptop for all your needs.</p>
// </div>

ในตัวอย่างนี้ เราได้ใช้ Template Literals เพื่อสร้าง HTML string สำหรับแสดงข้อมูลของสินค้า การใช้ ${} ทำให้เราสามารถแทรกค่าของ properties ของ object product ลงใน HTML string ได้อย่างง่ายดาย

Tagged Templates (Optional)

Template Literals ยังมีคุณสมบัติที่เรียกว่า Tagged Templates ซึ่งเป็น advanced feature ที่ช่วยให้เราสามารถควบคุมการประมวลผลของ Template Literals ได้

Tagged Templates คือการเรียกใช้ฟังก์ชันโดยใช้ Template Literal เป็น argument ฟังก์ชันที่ถูกเรียกใช้จะได้รับ array ของ string parts และ array ของ values ที่ถูกแทรกเข้าไป

function highlight(strings, ...values) {
  let result = "";
  for (let i = 0; i < strings.length; i++) {
    result += strings[i];
    if (i < values.length) {
      result += `<mark>${values[i]}</mark>`;
    }
  }
  return result;
}

const name = "Alice";
const profession = "developer";

const highlightedText = highlight`Hello, my name is ${name} and I am a ${profession}.`;
console.log(highlightedText);
// Output: Hello, my name is <mark>Alice</mark> and I am a <mark>developer</mark>.

ในตัวอย่างนี้ ฟังก์ชัน highlight ได้รับ array ของ string parts (strings) และ array ของ values (values) จากนั้นฟังก์ชันจะทำการสร้าง string ใหม่โดยการแทรก <mark> tag รอบๆ values

Tagged Templates เป็นเครื่องมือที่มีประโยชน์สำหรับการทำ string escaping, localization, หรือการสร้าง domain-specific languages (DSLs)

สรุป

Template Literals เป็นเครื่องมือที่มีประสิทธิภาพที่ช่วยให้การจัดการ string ใน JavaScript เป็นเรื่องง่ายและสะดวกมากยิ่งขึ้น ด้วยคุณสมบัติการแทรกตัวแปร (String Interpolation) และการสร้าง Multiline Strings ทำให้ Template Literals เป็นสิ่งที่ขาดไม่ได้สำหรับการพัฒนาเว็บสมัยใหม่

ในบทความถัดไป เราจะมาเรียนรู้เกี่ยวกับ Arrow Functions ซึ่งเป็นอีกหนึ่ง feature ที่สำคัญของ JavaScript ที่ช่วยให้การเขียนฟังก์ชันสั้นและกระชับมากยิ่งขึ้น

Office.in.th Custom Service

ต้องการพัฒนาระบบหรือปรับแต่งจากโครงสร้างนี้?

Office.in.th รับพัฒนาและออกแบบ Enterprise Web Application, API Integration และระบบบริหารงานภาครัฐ/เอกชน พร้อมการสนับสนุนระยะยาว

ดูบริการรับพัฒนาซอฟต์แวร์