How to Format Strings in TypeScript ?
Last Updated :
16 Jul, 2024
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall presentation and functionality of the code.
There are several ways to format the string in TypeScript which are as follows:
Using Concatenation (+)
The concatenation operator (+) joins strings together. In this method, variables are combined with static text to create a final formatted string.
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
Template literals allow embedding variables directly into a string by enclosing the string within backticks (``). The ${} syntax is used to insert variables into the string.
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
The eval() function can be used for string interpolation within a regular string. By wrapping the string in backticks and using ${} placeholders, eval() evaluates the expression and replaces placeholders with their corresponding values.
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."
Using the String.format Method
While TypeScript does not have a built-in String.format method like some other languages, we can create a custom String.format function to achieve similar functionality. This approach allows for more flexible and readable string formatting by using placeholders in the string.
Example: The following example demonstrates how to use a custom String.format function to format strings in TypeScript.
JavaScript
// Custom String.format function
function formatString(template: string, ...args: any[]): string {
return template.replace(/{(\d+)}/g, (match, index) => {
return typeof args[index] !== 'undefined' ? args[index] : match;
});
}
const template = "Visit {0} for {1} articles.";
const website = "GeeksforGeeks";
const topic = "Programming";
const result = formatString(template, website, topic);
console.log(result);
Output:
Visit GeeksforGeeks for Programming articles.
Similar Reads
How to Convert String to Date in TypeScript ? In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC.Table of ContentUsing new Date()Using Date.parse() Using Date.UTC()Using new Date()In this approac
2 min read
How to Format Date in TypeScript ? Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this. Below are the methods to format the date data type in TypeScript:Table of ContentUsing toLocaleString() methodUsing toLocaleDateString() met
3 min read
How to Convert String to JSON in TypeScript ? Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript:Table of ContentConvert String to JSON Using JSON.parse()Convert String to
5 min read
How to Convert String to Number in TypeScript? In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application. Below are the approaches to convert string to number in TypeSc
4 min read
How to Convert a String to enum in TypeScript? In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript.These are the two approaches that can be used to solve it:Table of ContentUsi
5 min read
How to Remove Spaces from a String in TypeScript ? TypeScript offers various inbuilt functions to remove spaces from a string. These functions can be used to remove spaces between characters or entire words. Below, we explore different approaches to remove spaces from a string in TypeScript.Table of ContentUsing split() and join() methodsUsing repla
4 min read
How to Declare an Array of Strings in TypeScript ? Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently. Below are the approaches to declare an Array of strings in TypeScript:Table of ContentSquare Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets notati
1 min read
TypeScript String trim() Method The TypeScript String trim() method is used to remove whitespace from both sides of a string. This method is also available in JavaScript because it is a subset of TypeScript. It returns a new string without leading or trailing spacesSyntaxstring.trim()Parameters:This method does not take any parame
2 min read
How to parse JSON string in Typescript? In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
3 min read
TypeScript String toString() Method The toString() method in TypeScript is a built-in function used to return a string representation of the specified object. This method is particularly useful when you need to convert various types of objects to their string forms.SyntaxThe syntax for using the toString() method is straightforward:st
2 min read