Back to JavaScript Fundamentals

How to format strings with variables in JavaScript

To format a string with variables in JavaScript, you can use template literals, string concatenation, and other methods. Let's dive into the different ways to format strings with variables in JavaScript.
4 min readLogan FordLogan Ford

How to format strings with variables in JavaScript?

String formatting with variables is a crucial skill in JavaScript programming. Whether you're creating dynamic messages, building templates, or working with user data, knowing how to combine strings with variables efficiently will make your code cleaner and more maintainable.

Template Literals (Template Strings)

Template literals, introduced in ES6, are the modern way to format strings with variables in JavaScript. They use backticks (`) and $ for variable interpolation. Backticks are different from single quotes and double quotes. They allow you to use variables and expressions inside the string without concatenation.

Basic Syntax and Usage

Take the following example on how to create strings with variables in JavaScript:

1// Basic template literal
2const name = 'John';
3const greeting = `Hello, ${name}!`;
4console.log(greeting); // Output: Hello, John!
5
6// Multiple variables
7const item = 'coffee';
8const price = 4.99;
9const message = `Your ${item} costs $${price}`;
10console.log(message); // Output: Your coffee costs $4.99
11
12// Expressions inside template literals
13const quantity = 3;
14const total = `Total: $${quantity * price}`;
15console.log(total); // Output: Total: $14.97

As demonstrated in the example above, you can use backticks to create strings with variables in JavaScript. Also take note that you must use the dollar sign ($) with curly braces ({}) to interpolate the variables.

Multiline Strings

Template literals make it easy to create multiline strings:


1const email = `
2Dear ${name},
3
4Thank you for your order of ${quantity} ${item}(s).
5Your total is $${quantity * price}.
6
7Best regards,
8The Store Team
9`;
10
11console.log(email);
12
13// Output:
14// Dear John,
15//
16// Thank you for your order of 3 coffee(s).
17// Your total is $14.97.
18//
19// Best regards,
20// The Store Team

String Concatenation Methods

While template literals are preferred, it's important to know other string formatting methods:

1// Using the + operator
2const name = 'Jane';
3const age = 25;
4const message1 = 'My name is ' + name + ' and I am ' + age + ' years old.';
5
6// Using concat()
7const message2 = ''.concat('My name is ', name, ' and I am ', age, ' years old.');
8
9// Using join()
10const message3 = ['My name is', name, 'and I am', age, 'years old'].join(' ');
11
12// Modern approach with template literals
13const message4 = `My name is ${name} and I am ${age} years old.`;

Number Formatting

JavaScript provides several powerful methods for formatting numbers, especially when working with currency values. Let's explore the key approaches:

1const price = 1234.5678;
2
3// Basic decimal formatting with toFixed()
4// toFixed() rounds to specified decimal places
5const formattedPrice = `$${price.toFixed(2)}`; // $1234.57
6const roundedPrice = `$${price.toFixed(0)}`; // $1235
7
8// Using Intl.NumberFormat for locale-aware formatting
9// This is the recommended way to format currency
10const formatter = new Intl.NumberFormat('en-US', {
11 style: 'currency',
12 currency: 'USD',
13 minimumFractionDigits: 2,
14 maximumFractionDigits: 2
15});
16const currencyString = formatter.format(price); // $1,234.57
17
18// Other number formatting options
19const percentFormatter = new Intl.NumberFormat('en-US', {
20 style: 'percent',
21 minimumFractionDigits: 1
22});
23const percentage = percentFormatter.format(0.3467); // 34.7%
24
25// Formatting large numbers
26const bigNumber = 1234567.89;
27const numberFormatter = new Intl.NumberFormat('en-US');
28const formattedBigNumber = numberFormatter.format(bigNumber); // 1,234,567.89

Date Formatting

JavaScript's Date object combined with template literals offers flexible date formatting options. Here's a comprehensive look:

1const date = new Date();
2
3// Basic date formatting methods
4const simpleDate = `Date: ${date.toLocaleDateString()}`; // e.g., "3/14/2024"
5const simpleTime = `Time: ${date.toLocaleTimeString()}`; // e.g., "2:30:45 PM"
6const fullDateTime = `DateTime: ${date.toLocaleString()}`; // e.g., "3/14/2024, 2:30:45 PM"
7
8// Advanced formatting with options
9const options = {
10 weekday: 'long', // full weekday name
11 year: 'numeric', // 4-digit year
12 month: 'long', // full month name
13 day: 'numeric', // day of the month
14 hour: '2-digit', // 2-digit hours
15 minute: '2-digit', // 2-digit minutes
16 timeZoneName: 'short' // time zone abbreviation
17};
18const fullDate = `Today is ${date.toLocaleDateString('en-US', options)}`;
19// e.g., "Today is Thursday, March 14, 2024, 02:30 PM EST"
20
21// Formatting specific date components
22const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
23 'July', 'August', 'September', 'October', 'November', 'December'];
24const customDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
25// e.g., "March 14, 2024"

Common Use Cases

1. Dynamic HTML Templates

1const user = {
2 name: 'Alice',
3 avatar: 'avatar.jpg',
4 role: 'Admin'
5};
6
7const userCard = `
8 <div class="user-card">
9 <img src="${user.avatar}" alt="${user.name}'s avatar">
10 <h2>${user.name}</h2>
11 <span class="role">${user.role}</span>
12 </div>
13`;

2. URL Construction

URL construction is a common use case for template literals, especially when building API endpoints or navigation links. Template literals make it easy to combine multiple URL components in a clean and readable way.

1const baseUrl = 'https://api.example.com';
2const endpoint = 'users';
3const id = 123;
4const query = 'status=active';
5
6// Template literals allow us to cleanly combine URL parts
7const url = `${baseUrl}/${endpoint}/${id}?${query}`;
8// https://api.example.com/users/123?status=active
9
10// This is much cleaner than concatenation:
11// const url = baseUrl + '/' + endpoint + '/' + id + '?' + query;
12
13// You can also handle multiple query parameters:
14const queryParams = {
15status: 'active',
16role: 'admin',
17limit: 10
18};
19const queryString = Object.entries(queryParams)
20.map(([key, value]) => `${key}=${value}`)
21.join('&');
22
23const urlWithMultipleParams = `${baseUrl}/${endpoint}?${queryString}`;
24// https://api.example.com/users?status=active&role=admin&limit=10

Template literals are particularly useful for URL construction because they:

  • Eliminate the need for messy string concatenation
  • Make the URL structure visually clear
  • Allow easy insertion of variables and parameters
  • Support multi-line formatting for complex URLs

Best Practices

  1. Use Template Literals by Default

    • More readable and maintainable
    • Better handling of multiline strings
    • Cleaner syntax for variable interpolation
  2. Format Numbers and Dates Appropriately

    • Use toFixed() for decimal precision
    • Utilize Intl.NumberFormat for localized numbers
    • Apply toLocaleDateString() for dates
  3. Handle Edge Cases

    • Check for null or undefined values
    • Provide default values when needed
    • Sanitize user input
  4. Keep it Clean

    • Break long strings into smaller parts
    • Use meaningful variable names
    • Comment complex string formatting logic

Practice Examples

Try these exercises to improve your string formatting skills:

  1. Create a template for an email notification system
  2. Build a dynamic URL builder with multiple parameters
  3. Format a complex data object into a readable string

Test your knowledge with these practice questions:


How to Concatenate Strings Using Template Literals in JavaScript to Create a Greeting Message
Easy
JavascriptTemplate literalsString concatenation+1

Ready to master JavaScript string formatting? Join TechBlitz for daily coding challenges, personalized learning paths, and a supportive community of developers. Start your journey today at TechBlitz.

Learn to code, faster

Join 810+ developers who are accelerating their coding skills with TechBlitz.

Share this article