String.Format like C# in typescript

I think you are looking for back quote: ``

var firstname = 'Fooo';
var lastname = 'Bar';

console.log(`Hi ${firstname} ${lastname}. Welcome.`);

You can find the back quote on the tilde key. enter image description here


Expanding on the comment that I made on the response from vivekkurien, declaring a function which, in turn, interpolates is probably the largest "bang for your buck" approach. I use this, frequently, for generating chunks of repetitive HTML with minor varying properties, for example.

The answer from vivekkurien, however, does not work. It returns a literal string, instead. Here is a modified sample, based on the original answer:

const pathFn = (param1, param2) => `path/${param1}/${param2}/data.xml`;

let param1 = "student";
let param2 = "contantdetails";
let resultPath = pathFn(param1, param2);

alert(resultPath);

A runnable example of the above code can be found here: Function-Based Interpolation at TypeScript Playground


const StringFormat = (str: string, ...args: string[]) =>
  str.replace(/{(\d+)}/g, (match, index) => args[index] || '')

let res = StringFormat("Hello {0}", "World!")
console.log(res) // Hello World!
res = StringFormat("Hello {0} {1}", "beautiful", "World!")
console.log(res) // Hello beautiful World!
res = StringFormat("Hello {0},{0}!", "beauty")
console.log(res) //Hello beauty,beauty!
res = StringFormat("Hello {0},{0}!", "beauty", "World!")
console.log(res) //Hello beauty,beauty!

Try in TypeScript Playgroud

Tags:

Typescript