Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Format Date in TypeScript ?
Next article icon

How to Format Strings in TypeScript ?

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using Concatenation (+)
  • Using Template Literals
  • Using eval() function

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.

Next Article
How to Format Date in TypeScript ?

A

anjalibo6rb0
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

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 Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
    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 Content Using toLocaleString() methodUsing toLocaleDateString() m
    4 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 Content Convert String to JSON Using JSON.parse()Convert String
    6 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 Content
    5 min read
  • How to Convert String to Boolean in TypeScript ?
    In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodU
    4 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 Content Using split() and join() methodsUsing rep
    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 Content Square Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets nota
    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 spaces Syntaxstring.trim()Parameters:This method does not take any param
    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
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences