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.
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 });
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.
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.
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}` .
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}`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With