Home > Web Front-end > JS Tutorial > How Can I Convert a Regular String to a Template Literal in ES6 JavaScript Without Using `eval` or `new Function`?

How Can I Convert a Regular String to a Template Literal in ES6 JavaScript Without Using `eval` or `new Function`?

Barbara Streisand
Release: 2024-11-27 08:24:10
Original
537 people have browsed it

How Can I Convert a Regular String to a Template Literal in ES6 JavaScript Without Using `eval` or `new Function`?

Converting a String to a Template String with ES6

In JavaScript, template strings allow you to embed expressions and variables directly into strings, providing a concise and readable syntax. However, what if you want to create a template string from an existing non-template string? This question explores the possibility of achieving this conversion without using dynamic code generation techniques like eval or new Function.

The provided solution leverages ES6's string interpolation capabilities with a custom interpolate function. This function takes an object containing the template parameters and dynamically generates a template string using a JavaScript template literal.

Here's how the solution works:

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

The interpolate function is added as a custom prototype method to the String object. It accepts an object of key-value pairs representing the template parameters.

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

Here, we apply the interpolate function to our template string, passing an object with the parameter text set to 'Foo Boo'. The function creates a template string by utilizing a JavaScript template literal with placeholders for the parameter values.

console.log(result);
Copy after login

Finally, we log the result to the console, which should output:

Example text: Foo Boo
Copy after login

This solution allows you to convert an ordinary string into a template string dynamically, enabling you to take advantage of the expressiveness and readability offered by template strings in your JavaScript code.

The above is the detailed content of How Can I Convert a Regular String to a Template Literal in ES6 JavaScript Without Using `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