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 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
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
Java String Manipulation: Best Practices For Clean Code In Java, a string is an object that represents a sequence of characters. It is a widely used data type for storing and manipulating textual data. The String class in Java is provided as a part of the Java standard library and offers various methods to perform operations on strings. Strings are funda
7 min read
String Handling with Apache Commons' StringUtils Class in Java The Apache Commons Lang library is a popular third-party library for working with Strings in Java, and the StringUtils class is a key part of this library. StringUtils is a utility class that provides a wide range of String manipulation methods that are not available in the standard Java String clas
9 min read
Console format(String, Object) method in Java with Examples The format(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. Syntax: public Console format(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It re
2 min read
Format Specifiers in Java Format specifiers begin with a percent character (%) and terminate with a "type character, " which indicates the type of data (int, float, etc.) that will be converted the basic manner in which the data will be represented (decimal, hexadecimal, etc.) The general syntax of a format specifier is % [f
8 min read
ChoiceFormat format() method in Java with Examples The format() method of java.text.ChoiceFormat class is used to get the appended string builder of the format value of particular limit value passed as parameter and text passed as parameter in this method. Syntax: public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition statu
2 min read
MessageFormat format() method in Java with Example : Set - 1 The format() method of java.text.MessageFormat class is used to get the formatted array of object appended into the string buffer object. formatted array will contain all forms of element lies in the pattern of MessageFormat object.Syntax: public final StringBuffer format(Object[] arguments, StringB
3 min read