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

How to Defer ES6 Template Literal Evaluation?

Patricia Arquette
Release: 2024-11-09 00:30:02
Original
807 people have browsed it

How to Defer ES6 Template Literal Evaluation?

Deferring Evaluation for ES6 Template Literals

In ES6, template literals allow for string interpolation with dynamic values. However, sometimes we may need to defer the evaluation of the template literal until a later point to incorporate dynamic elements.

Question: How can we write code to defer the evaluation of an ES6 template literal until after we have dynamically created the elements used for interpolation?

Answer: There are several approaches to achieving this:

  1. Using Plain Strings:

    Utilize plain string literals instead of template strings to avoid immediate evaluation. The interpolation placeholder values can be formatted using a custom prototype method like this:

    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
  2. Using Tagged Template Literals:

    Tagged template literals offer an alternative method. However, it's important to note that substitutions are still evaluated without allowing for interpolation of identifiers like "p0".

    function formatter(literals, ...substitutions) {
        return {
            format: function() {
                var out = [];
                for(var i=0, k=0; i < literals.length; i++) {
                    out[k++] = literals[i];
                    out[k++] = arguments[substitutions[i]];
                }
                out[k] = literals[i];
                return out.join("");
            }
        };
    }
    console.log(formatter`Hello, <pre class="brush:php;toolbar:false">console.log(`Hello, ${"world"}. This is a ${"test"}`);
    Copy after login
    . This is a `.format("world", "test"));
  3. Avoiding Deferral:

    Consider using template strings as intended without any format function or deferral. Template strings provide a concise and efficient way to interpolate dynamic values without additional complexity.

The above is the detailed content of How to Defer ES6 Template Literal Evaluation?. 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