Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda