Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
Is it possible to predefine the template literal in ECMAScript 6 and reuse many times?

template literal

For example,

//define a template literal
let template = `Hello {target}`;

//Then reuse it, just examples to show the idea
let str1 = Format(template, "World");//str1 becomes "Hello World"
let str2 = Format(template, "There");//str2 becomes "Hello There"
let str3 = Format(template, "There Again");//str3 becomes "Hello There Again"

BTW, it's a common practice to reuse template string by string.Format in C#:

string template = `Hello {0}`;
string str1 = string.Format(template, "World");//str1 becomes "Hello World"
string str2 = string.Format(template, "There");//str2 becomes "Hello There"
string str3 = string.Format(template, "There Again");//str3 becomes "Hello There Again"

The question is, can it be done with ES6?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It can be done similarly by using a function:

function GetHelloStr(target){
  return `Hello ${target}`;
}
let str1 = GetHelloStr("World");
let str2 = GetHelloStr("There");
let str3 = GetHelloStr("There Again");

But in this case, the template string is not reused. Every call of GetHelloStr will create a new string, which isn't performant.

It can be done similarly by tagged templates

function HelloStr(strings, target){
  return `Hello ${target}`;
}
let str1 = HelloStr`${'World'}`;
let str2 = HelloStr`${'There'}`;
let str3 = HelloStr`${'There Again'}`;

This also doesn't reuse the template string. I'd rather use the function approach.

Also I found a library which exactly handles such cases: https://github.com/davidchambers/string-format

Sadly, none of those is elegant as string.Format from C#.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda