Open In App

JavaScript String Formatting

Last Updated : 30 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript string formatting refers to the technique of inserting variables, expressions, or values into strings to make them dynamic and readable. It can be done using methods like concatenation, template literals (backticks), and custom formatting functions, which help create flexible and clean string outputs in your code.

Approaches for JavaScript String Formatting

1. Using Concatenation (Traditional Approach)

This method joins strings and variables using the + operator. It's simple, but not as clean or readable as newer methods like template literals.

JavaScript
const name = "Amit";
const age = 99;
const message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);

Output
Hello, my name is Amit and I am 99 years old.
  • Strings are combined using the + operator.
  • Variables are directly appended to the string.

Common Mistake: Math Inside Strings

If you insert an arithmetic expression into a string without parentheses, JavaScript may treat the numbers as strings and concatenate them instead of performing math. This can lead to unexpected results.

JavaScript
let result1 = "Total: " + 10 + 5;
console.log(result1);

2. Custom String Formatting with {} Placeholders

JavaScript, unlike languages like C# or Python, doesn’t support built-in string formatting using {} placeholders. To use this pattern, you'll need to create a custom function that replaces {0}, {1}, etc., with values you provide.

JavaScript
function format(str, ...values) {
  return str.replace(/{(\d+)}/g, function(match, index) {
    return typeof values[index] !== 'undefined' ? values[index] : match;
  });
}

// Usage
let formattedStr = format("Hello, {0}! You have {1} new messages.", "GeeksforGeeks", 5);
console.log(formattedStr); 

Output
Hello, GeeksforGeeks! You have 5 new messages.

In this Example:

  • The format function takes a string (str) and a list of values (...values) you want to insert into that string.
  • Inside the function, we use str.replace() to find placeholders like {0}, {1}, and so on, in the string.
  • The replace() method looks for these placeholders using a regular expression (/{(\d+)}/g) and then passes each match to the function inside.
  • For each placeholder, the function checks if the corresponding value (like "GeeksforGeeks" or 5) exists and replaces the placeholder with that value. If no value is found, it leaves the placeholder as is.
  • In the example, calling format("Hello, {0}! You have {1} new messages.", "GeeksforGeeks", 5) replaces {0} with "GeeksforGeeks" and {1} with 5, creating the final string: "Hello, GeeksforGeeks! You have 5 new messages."

3. Using Backticks (Template Literals)

One of the simplest Method a string in JavaScript is by using template literals (also known as string interpolation). Instead of enclosing the string with single (') or double (") quotes, you use backticks (`).

Variables can be embedded directly into the string by wrapping them in ${}. During runtime, JavaScript automatically evaluates and inserts the variable’s value, making the code more readable and dynamic.

JavaScript
const name = "Amit";
const age = 99;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);

Output
Hello, my name is Amit and I am 99 years old.
  • ${expression}: Interpolates variables or expressions directly into the string.
  • Backticks allow multi-line strings and better readability.

4. Using String Interpolation (with Expressions)

Template literals in JavaScript allow you to embed not just simple variables but also expressions inside ${} placeholders. This makes string formatting more flexible and powerful, as you can directly include calculations or function calls within the string.

JavaScript
const a = 5;
const b = 10;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);

Output
The sum of 5 and 10 is 15.

Expressions like a + b are evaluated before being inserted into the string.

5. Using concat() Method

The concat() method is an alternative to the + operator for combining strings, though it's less commonly used in modern JavaScript.

JavaScript
const s1 = "Hello";
const s2 = "World";
const message = s1.concat(", ", s2, "!");
console.log(message);

Output
Hello, World!
  • concat() appends multiple strings together.
  • Useful for chaining multiple strings, though less readable than template literals.

Which Method to Choose?

1. Template Literals (Backticks)

  • Best for readability and flexibility.
  • Allows embedding variables and expressions directly.
  • Ideal for dynamic and multi-line strings.

2. Concatenation (+ operator)

  • Simple, but can get messy with complex strings.

3. concat() Method

  • Less commonly used, but good for explicitly joining strings.

4. Custom Formatting with {} Placeholders

  • Less commonly used, but good for explicitly joining strings.

Note: Use template literals for most cases as they are cleaner and more flexible.


Next Article

Similar Reads