Home > Web Front-end > JS Tutorial > Understanding Tagged Template Literals in JavaScript

Understanding Tagged Template Literals in JavaScript

WBOY
Release: 2024-08-05 20:06:06
Original
680 people have browsed it

Understanding Tagged Template Literals in JavaScript

What are Tagged Template Literals?

A tagged template literal involves a template literal prefixed with a function, called a tag. This function can process and manipulate the literal's content. Here's a simple example:

function tag(strings, ...values) {
    console.log(strings);
    console.log(values);
    return 'Processed string';
}

const name = 'Alice';
const greeting = tag`Hello, ${name}! How are you?`;
console.log(greeting);
Copy after login

Use Cases for Tagged Template Literals

  1. Internationalization (i18n)

Tagged template literals can dynamically translate strings based on the user’s locale. Here’s an example using Japanese:

function i18n(strings, ...values) {
    const translations = {
        'Hello, ': 'こんにちは、',
        '! How are you?': '!元気ですか?',
    };

    return strings.reduce((result, str, i) => result + translations[str] + (values[i] || ''), '');
}

const name = 'アリス';
const greeting = i18n`Hello, ${name}! How are you?`;
console.log(greeting); // Output: "こんにちは、アリス!元気ですか?"

Copy after login

2. Custom String Formatting

They can also implement custom formatting logic, such as escaping HTML.

function escapeHTML(strings, ...values) {
    const escape = (str) => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return strings.reduce((result, str, i) => result + str + escape(values[i] || ''), '');
}

const userInput = '<script>alert("XSS")</script>';
const sanitized = escapeHTML`User input: ${userInput}`;
console.log(sanitized); // Output: "User input: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;"
Copy after login

Conclusion

Tagged template literals provide a versatile tool for dynamic string manipulation in JavaScript. They can simplify tasks like internationalization and custom string formatting, leading to more expressive and maintainable code.

The above is the detailed content of Understanding Tagged Template Literals in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template