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

How to Defer Template Literal Execution in ES6?

Linda Hamilton
Release: 2024-11-09 13:51:03
Original
620 people have browsed it

How to Defer Template Literal Execution in ES6?

Deferring Template Literal Execution in ES6

In ES6, template literals provide a powerful way to embed dynamic values into strings. However, when using string interpolation within template literals, the values are evaluated before the template literal is processed by custom string manipulation methods. This can lead to undesired results when deferring the execution of the template literal.

To address this, there are several approaches one can consider:

1. Utilize Template Strings

Avoid using string interpolation within template literals and instead opt for template strings as intended. For instance:

console.log(`Hello, ${"world"}. This is a ${"test"}`);
Copy after login

2. Employ Tagged Template Literals

Leverage tagged template literals to execute code after the template literal substitutions have been evaluated. However, it's important to note that the substitutions themselves are still evaluated immediately:

function formatter(literals, ...substitutions) {
  return {
    format: function() {
      // Implementation for value substitution and template literal concatenation
    }
  };
}
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"));

3. Use Plain String Literals with Custom String Manipulation

Create a custom string manipulation function to format the string later in the code, after values have been retrieved dynamically:

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