>  기사  >  웹 프론트엔드  >  JavaScript의 태그된 템플릿 리터럴 이해

JavaScript의 태그된 템플릿 리터럴 이해

WBOY
WBOY원래의
2024-08-05 20:06:06627검색

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);

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: "こんにちは、アリス!元気ですか?"

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;"

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.

위 내용은 JavaScript의 태그된 템플릿 리터럴 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.