Open In App

How to Format Strings in TypeScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, the formatting of strings consists of structuring and concatenating the strings to make them in a properly readable format. We can use various approaches to format the strings in TypeScript.

There are several ways to format the string in TypeScript which are as follows:

Using Concatenation (+)

In this approach, we are using the concatenation operator + to join strings together. The variables website and category are concatenated with the static text to create the final string stored in the message variable.

Syntax:

let result: string = string1 + string2;

Example: The below example uses Concatenation (+) to format strings in TypeScript.

Javascript




let website: string = "GeeksforGeeks";
let category: string = "Programming";
let message: string =
    "Visit " + website + " for " + category + " articles.";
console.log(message);


Output:

"Visit GeeksforGeeks for Programming articles." 

Using Template Literals

In this approach, template literals are used by enclosing the string within backticks (“). Variables like website and category are added directly into the string using ${} syntax. The output message variable is then printed to the console.

Syntax:

let result: string = `String content with ${variable1} and ${variable2}`; 

Example: The below example uses Template Literals to format strings in TypeScript.

Javascript




let website: string = "GeeksforGeeks";
let category: string = "Programming";
let message: string =
    `Visit ${website} for ${category} articles.`;
console.log(message);


Output:

"Visit GeeksforGeeks for Programming articles." 

Using eval() function

In this approach, we are using the eval() function to perform string interpolation within a regular string. By wrapping the string in backticks and using ${} placeholders, the eval() function is used to evaluate the expression, by replacing ${website} and ${category} with their corresponding values, printing in the final formatted string.

Syntax:

let result: string = eval("`String content with ${variable1} and ${variable2}`");

Example: The below example uses the eval() function to format strings in TypeScript.

Javascript




let website: string = "GeeksforGeeks";
let category: string = "Programming";
let message: string =
    "Visit ${website} for ${category} articles.";
console.log(eval("`" + message + "`"));


Output:

"Visit GeeksforGeeks for Programming articles." 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads