String interpolation in Typescript, replacing 'placeholders' with variables

monstertjie_za picture monstertjie_za · Sep 6, 2018 · Viewed 23k times · Source

I cannot seem to find a clear enough answer on this topic, so I am asking the question:

In C#, I can do the following, for instance:

var text = "blah blah";
var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah'

How would I achieve this in Typescript?

Usage:

I am loading a URL from the environment.ts file, and this string URL will need to contain the placeholders, and in my service layer, replace the placeholders with the actual parameters that needs to be passed in.

Answer

basarat picture basarat · Sep 6, 2018

Use a template string which are much better than String.Format in my opinion as they do not suffer from poor indexing (wrong placeholder) issues:

var text = "blah blah";
var strTest = `This is a ${text}`;
console.log(strTest);

If I do not know the name of the variables I need to pass in??

Then wrap in a function e.g.

const gen = (text) => `This is a ${text}`;