Home > Web Front-end > JS Tutorial > body text

How to Defer Evaluation of ES6 Template Literals?

Susan Sarandon
Release: 2024-11-06 20:42:03
Original
427 people have browsed it

How to Defer Evaluation of ES6 Template Literals?

Deferring Execution for ES6 Template Literals

ES6 Template Literals provide a powerful syntactic sugar for string interpolation, but what if you want to defer evaluation until after dynamic element creation?

The Issue

Traditionally, using String.prototype.format would allow deferred evaluation. However, template literals are evaluated at parse time, preventing this approach.

Solution 1: Use Tagged Template Literals

Tagged template literals allow you to intercept and process the template literal before evaluation:

function formatter(literals, ...substitutions) {
    return {
        format: function() {
            // ... code here ...
        }
    };
}
console.log(formatter`Hello, <pre class="brush:php;toolbar:false">String.prototype.format = function() {
    var args = arguments;
    return this.replace(/$\{p(\d)\}/g, function(match, id) {
        return args[id];
    });
};
console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
Copy after login
. This is a `.format("world", "test"));

Solution 2: Use Plain String Literals

Alternatively, you can use plain string literals and manually parse the substitutions:

const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
console.log(welcome("world", "test"));
Copy after login

Solution 3: Avoid Template Literals and Use Function Parameters

Finally, you can avoid template literals altogether and use function parameters:

Considerations

  • Solution 1 offers the most flexibility but may be overly complex for simple use cases.
  • Solution 2 is more straightforward but requires manual parsing.
  • Solution 3 uses a traditional approach without template literals.

The above is the detailed content of How to Defer Evaluation of ES6 Template Literals?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!