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 Text Formatting
JavaScript has many inbuilt features to format the text. Texts are the strings in JavaScript. There are many formatting styles like making text uppercase, lowercase, bold, and italic. Below are several formatting styles in JavaScript which are as follows: Table of Content Making text UpperCaseMaking
2 min read
Less.js String % format() Function
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. Since CSS is a dynamic style sheet language, it is preferred. Because LESS is adaptable, it can be used by a variety of browsers. Only CSS that has been created an
4 min read
JavaScript String Methods
JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
11 min read
JavaScript Strings Coding Practice Problems
Strings are one of the most essential data types in JavaScript, used for handling and manipulating text-based data. This curated list of JavaScript string practice problems covers everything master JavaScript Strings. Whether you're a beginner or an experienced developer, these problems will enhance
1 min read
JavaScript String padEnd() Method
The padEnd() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the right end of the string.Syntax:string.padEnd( targetLength, padString );Parameters: This method accepts two parameters as mentioned above and described bel
3 min read
PHP sprintf() Function
The sprintf() function is an inbuilt function in PHP that is used for formatting strings in a manner similar to the C language's printf() function. It allows you to create formatted strings by substituting placeholders with corresponding values. Syntax: string sprintf(string $format, mixed ...$value
2 min read
PHP | Format Specifiers
Strings are one of the most used Datatype arguably irrespective of the programming language. Strings can be either hardcoded (specified directly by the developer) or formatted (where the basic skeleton is specified and the final string is obtained by incorporating values of other variables). Formatt
5 min read
Java String format() Method
In Java, the String.format() method allows us to create a formatted string using a specified format string and arguments. We can concatenate the strings using this method, and at the same time, we can format the output with options such as width, alignment, decimal places, and more.Example: In the e
4 min read
PrintWriter format(String, Object) method in Java with Examples
The format(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(String format, Object...args) Parameters: This method accepts two
2 min read
PrintStream format(String, Object) method in Java with Examples
The format(String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(String format, Object...args) Parameters: This method accepts two
2 min read