0

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?

zwcloud
  • 4,546
  • 3
  • 40
  • 69
  • 1
    Though stereotypical for SO, the highest voted answer on the dupe target is absolutely horrendous, and one should read the second highest instead. – ASDFGerte Jun 27 '22 at 15:23

1 Answers1

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#.

zwcloud
  • 4,546
  • 3
  • 40
  • 69