Home > Web Front-end > JS Tutorial > How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?

How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?

Mary-Kate Olsen
Release: 2024-11-22 10:05:14
Original
762 people have browsed it

How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?

Transforming Simple Strings into Template Strings

Can a regular string be effortlessly transformed into a template string? Consider the following example:

let a = "b:${b}";
Copy after login

How can we convert this into a template string dynamically, without resorting to eval, new Function, or other dynamic code generation techniques?

let b = 10;
console.log(a.template()); // b:10
Copy after login

An ES6 Solution

In modern JavaScript, we can leverage ES6 features to achieve this conversion:

String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
};

const template = 'Example text: ${text}';
const result = template.interpolate({
  text: 'Foo Boo'
});
console.log(result); // 'Example text: Foo Boo'
Copy after login

This method utilizes the String.prototype.interpolate function that accepts an object of parameters. It dynamically constructs a new function using the object's keys and values, then executes it to return the interpolated string.

The above is the detailed content of How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?. 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