JavaScript String Formatting
Last Updated :
30 Apr, 2025
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.
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);
OutputHello, 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);
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);
OutputHello, 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);
OutputHello, 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);
OutputThe 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);
- 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.
- Less commonly used, but good for explicitly joining strings.
Note: Use template literals for most cases as they are cleaner and more flexible.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Introduction to Tree Data Structure Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or
15+ min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read