String Formatting in JavaScript

String Formatting in JavaScript

JavaScript offers several ways to format strings, enabling you to create dynamic and readable output. While historically requiring custom functions or external libraries, modern JavaScript (ES6 and beyond) provides elegant built-in solutions. This tutorial explores common techniques for string formatting in JavaScript, ranging from basic number formatting to advanced template literals.

1. Basic String Concatenation

The simplest form of string formatting is concatenation using the + operator. However, this approach can quickly become cumbersome and difficult to read, especially with multiple variables.

let name = "Alice";
let age = 30;
let message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);

2. Template Literals (ES6+)

Template literals, introduced in ES6, offer a more readable and powerful way to format strings. They are delimited by backticks ( ) instead of single or double quotes and allow for easy variable interpolation using the ${variable} syntax.

let name = "Bob";
let age = 25;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);

Template literals are particularly useful for constructing complex strings, as they can span multiple lines without requiring concatenation. They also allow for the inclusion of expressions within the ${} placeholders.

3. Number Formatting

JavaScript provides built-in methods for formatting numbers to specific decimal places or using exponential notation.

3.1 toFixed()

The toFixed() method formats a number to a specified number of decimal places, rounding the result if necessary. It returns a string representation of the number.

let price = 12.345;
let formattedPrice = price.toFixed(2); // Returns "12.35"
console.log(formattedPrice);

3.2 toExponential()

The toExponential() method formats a number using exponential notation to a specified number of decimal places.

let largeNumber = 33333;
let exponentialForm = largeNumber.toExponential(2); // Returns "3.33e+4"
console.log(exponentialForm);

3.3 toString(radix)

The toString(radix) method converts a number to a string representation in a specified base (radix).

let decimalNumber = 255;
let hexadecimalNumber = decimalNumber.toString(16); // Returns "ff"
let binaryNumber = decimalNumber.toString(2); // Returns "11111111"
console.log(hexadecimalNumber, binaryNumber);

4. Custom Formatting Functions

For more complex formatting requirements, you can create custom functions. These functions can take a number or string as input and return a formatted string based on your specific needs. Consider the use of regular expressions for sophisticated pattern matching and replacement.

function formatCurrency(amount, currencySymbol) {
  return `${currencySymbol}${amount.toFixed(2)}`;
}

let price = 19.99;
let formattedPrice = formatCurrency(price, "$");
console.log(formattedPrice); // Output: $19.99

5. Utilizing String.prototype.format (Compatibility)

While template literals are the modern approach, you might encounter older code or scenarios where you need a String.format()-like function. You can extend the String prototype to add this functionality, but exercise caution when modifying built-in prototypes to avoid potential conflicts. Here’s an implementation:

if (!String.prototype.format) {
  String.prototype.format = function(args) {
    let str = this.toString();
    for (let key in args) {
      let regex = new RegExp("\\{" + key + "\\}", "g");
      str = str.replace(regex, args[key]);
    }
    return str;
  };
}

let message = "Hello, {name}! You are {age} years old.";
let formattedMessage = message.format({ name: "Charlie", age: 40 });
console.log(formattedMessage);

This example creates a function that replaces placeholders like {name} and {age} with the corresponding values from the args object.

Leave a Reply

Your email address will not be published. Required fields are marked *