String interpolation in Typescript, replacing 'placeholders' with variables

Viewed 44714

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.

4 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}`;

I'd suggest using anonymous generator functions in your environments.ts file, so you could pass the variables you need and have the template strings inside this functions. Something like this:

environments.ts

 export const thisIsA = (str: string) => `This is a ${str}`;

Some other file:

import * as env from 'environments';

var text = "blah blah";
var strTest = env.thisIsA(text); //output: 'This is a blah blah'

There is a npm package called localized-strings it has a formatString method which can be used for string interpolation in a C# fashion.

import LocalizedStrings, {LocalizedStringsMethods} from "localized-strings";

interface IStrings extends LocalizedStringsMethods{
}

const localizedStrings: IStrings  = new LocalizedStrings({en: {}});
const result = localizedStrings.formatString("This is a {0}", "Text").toString();
console.log(result);

More examples here

In your enviornment.ts:

export const str = "This is a {0} and this is {1}.";

Use while runtime, anywhere:

import * as env from 'environments';

console.log(env.str.replace('{0}', 'blah blah').replace('{1}', 'again a blah blah'));
Related