Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in Typescript, replacing 'placeholders' with variables

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.

like image 903
monstertjie_za Avatar asked Sep 06 '18 04:09

monstertjie_za


People also ask

How do you replace a placeholder in a string?

You can easily use it to replace placeholders by name with this single method call: StringUtils. replaceEach("There's an incorrect value '%(value)' in column # %(column)", new String[] { "%(value)", "%(column)" }, new String[] { x, y });

How do you specify string interpolation in TypeScript?

Use a template literal to interpolate variables in a string in TypeScript, e.g. hello ${myVariable} . Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

What is the correct syntax for string interpolation in JavaScript?

In order to make it readable, the developer has to maintain all the whitespaces. This is where ES6 comes to rescue with String interpolation. In JavaScript, the template literals (strings wrapped in backticks ` `) and ${expression} as placeholders perform the string interpolation.

Does JavaScript support string interpolation?

In JavaScript, the template string implements the string interpolation. A template string is defined by wrapping a sequence of characters into a pair of backticks `I'm template string` . The template string placeholders have the format ${expression} , for example `The number is ${number}` .


1 Answers

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}`;
like image 198
basarat Avatar answered Oct 16 '22 16:10

basarat