Home > Software > How to Use TypeScript String Formatting

How to Use TypeScript String Formatting

Anastasios Antoniadis

Share on X (Twitter) Share on Facebook Share on Pinterest Share on LinkedInTypeScript, a superset of JavaScript, offers robust tools and features for building scalable web applications. One of its many strengths lies in string manipulation and formatting, a fundamental aspect of programming that affects data display, user interfaces, and backend processing. This article delves …

TypeScript

TypeScript, a superset of JavaScript, offers robust tools and features for building scalable web applications. One of its many strengths lies in string manipulation and formatting, a fundamental aspect of programming that affects data display, user interfaces, and backend processing. This article delves into TypeScript string formatting, covering the basics to more advanced techniques, ensuring your codebase is both efficient and readable.

Introduction to String Formatting

String formatting involves constructing strings by dynamically inserting variables or expressions into placeholders within a string template. This process is crucial for creating messages, URLs, queries, and more, where static strings fall short.

Template Literals

Introduced in ES6 and fully supported by TypeScript, template literals (or template strings) are the cornerstone of string formatting in modern JavaScript and TypeScript. They provide an easy syntax for embedding expressions within strings.

const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!

Template literals use backticks (`) instead of single (‘ ‘) or double (” “) quotes and can span multiple lines, preserving newlines and spaces within the template.

const item = "coffee";
const price = 3.5;
const multilineString = `Item: ${item}
Price: $${price}`;
console.log(multilineString);

Tagged Template Literals

Tagged template literals allow parsing template literals through a function, offering a method for custom string manipulation. The tag function receives an array of string literals and the interpolated expressions, providing fine-grained control over the output string.

function currency(strings, ...values) {
  return strings.reduce((accumulator, part, i) => {
    return `${accumulator}${part}${values[i] ? `$${values[i].toFixed(2)}` : ''}`;
  }, '');
}

const price = 9.99;
const tax = 0.8;
const total = currency`Price: ${price}, Tax: ${tax}, Total: ${price + tax}`;
console.log(total); // Output: Price: $9.99, Tax: $0.80, Total: $10.79

Advanced Formatting Techniques

While template literals offer a great deal of flexibility, certain scenarios call for more specialized formatting solutions.

Padding and Alignment

Padding numbers or strings to ensure they meet a certain length can be achieved using String.prototype.padStart and String.prototype.padEnd.

const padNumber = (num: number, targetLength: number) => num.toString().padStart(targetLength, '0');
console.log(padNumber(5, 3)); // Output: 005

const padString = (str: string, targetLength: number) => str.padEnd(targetLength, ' ');
console.log(padString('TS', 5) + '|'); // Output: TS   |

Localization and Internationalization

For applications supporting multiple locales, displaying numbers, dates, and currencies in a locale-specific format is essential. TypeScript can leverage the Internationalization API available in modern JavaScript environments.

const number = 123456.789;
console.log(new Intl.NumberFormat('en-US').format(number)); // Output: 123,456.789 (in US English)

const date = new Date();
console.log(new Intl.DateTimeFormat('en-GB').format(date)); // Output: dd/mm/yyyy (in UK English format)

const currency = 99.99;
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(currency)); // Output: ¥100 (in Japanese Yen)

Custom Formatting Functions

For specific formatting needs not covered by built-in methods or when seeking to encapsulate repeated formatting logic, custom formatting functions are invaluable

function formatTemperature(celsius: number): string {
  return `${celsius.toFixed(1)}°C / ${(celsius * 9 / 5 + 32).toFixed(1)}°F`;
}
console.log(formatTemperature(30)); // Output: 30.0°C / 86.0°F

Conclusion

TypeScript enhances JavaScript’s string formatting capabilities, providing developers with powerful tools for creating dynamic, localized, and readable strings. From leveraging template literals for basic interpolation to employing the Internationalization API for locale-specific formats, TypeScript caters to a wide range of formatting needs. As you build more complex TypeScript applications, mastering string formatting will undoubtedly contribute to more maintainable, efficient, and user-friendly code.

Anastasios Antoniadis
Follow me
Latest posts by Anastasios Antoniadis (see all)
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x