16

Is it possible to use similar function like String.Format of C# in TypeScript?

My idea is to make some string like:

url = "path/{0}/{1}/data.xml"

depending of the logical I set {0} and {1}. Obiouslly I can replace them but I think String.Format is a clear function.

5 Answers 5

22

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

Sign up to request clarification or add additional context in comments.

1 Comment

String.format you can use an array and position 0 i the format and the next one are the values but all in an array of basic objects.
18
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

Comments

15

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

2 Comments

String.format you can use an array and position 0 i the format and the next one are the values but all in an array of basic objects. Is it possible to do in Typescript?
Not natively, that I am aware of. That being said, check out the second response to this question, which sounds very close to what you are looking for, there: stackoverflow.com/questions/20070158/…
2

You need to make the path as a function which can accept 2 parameter. Then it will return as string if we call the function with required parameters.

const pathFn= (param1, param2) => "path/${param1}/${param2}/data.xml";
let param1 = "student";
let param2 = "contantdetails";
let resultPath = pathFn(param1,param2);

1 Comment

You would want to use bat quotes for the string interpolation to kick in, as well as use the interpolation marker ($) for the replacement to happen. See: typescriptlang.org/play/…
1

This worked for me. Tried with different scenarios.

format(text: string, ...args: string[]): string {
    return text.replace(/{(\d+)}/g, (match, num) => {
      return typeof args[num] !== 'undefined' ? args[num] : match;
    });
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.