Home >Web Front-end >JS Tutorial >How to Defer Evaluation of ES6 Template Literals?

How to Defer Evaluation of ES6 Template Literals?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 20:42:03512browse

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

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!

Statement:
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