Strings are a primitive data type in JavaScript. You can use JavaScript string format to construct a string dynamically, with placeholders that you can replace with values at runtime. You may also need to format numbers and money values into strings sometimes. This is where string formatting in JavaScript comes in.
In this post, we’ll explore:
- Different ways to format variable string
- Format string using plus (+) sign
- Format using placeholder
- Using string interpolation to format string
- String format number
- string format money
Let’s look into each item in detail.
JavaScript string format in three different ways
One of the most common reasons to format a string is to print JavaScript variables in a string. There are many ways to format JavaScript strings.
In this article, we’ll look at the top three methods to format strings with variables.
1. Format JavaScript string using plus (+) sign
Using the plus sign (+)
to format the simple string is the traditional approach. With this method, you have to insert a JavaScript variable in a string separated by the + sign
. This approach resembles the JavaScript string concatenation process.
const customerName = "John";
const orderId = 10001;
console.log('Hello '+ customerName +', your order '+ orderId +' has been shipped.');
// Output: "Hello John, your order 10001 has been shipped."
If you insert any arithmetic expression in string formatting without parenthesis, you will get unexpected results.
The following example, for example, prints the unexpected result. This happens because the number converts to a string before adding another number.
console.log('Sum of 5+5 is ' + 5 + 5);
// Output: "Sub of 5+5 is 55."
You may simply solve this issue by enclosing integers in parentheses. In this situation, it will first total the integers and then add them to the string.
console.log('Sum of 5 + 5 is ' + (5 + 5));
// Output: "Sum of 5 + 5 is 10"
2. JavaScript format string using placeholder { }
Unlike other programming languages like C#
, JavaScript
does not support built string formatting functions with placeholders { }
.
We have to write custom JavaScript string format function
or string prototype methods.
const formatString = (template, ...args) => {
return template.replace(/{([0-9]+)}/g, function (match, index) {
return typeof args[index] === 'undefined' ? match : args[index];
});
}
console.log(formatString('Hello {0}, your order {1} has been shipped.', 'John', 10001));
// Output: "Hello John, your order 10001 has been shipped."
The above formatString()
method accepts template strings and args
as parameters. The regular expression
replaces each placeholder with the corresponding value from args
.
You can write this as a JavaScript string prototype
method, as shown in the below example:
String.prototype.format = function () {
var args = arguments;
return this.replace(/{([0-9]+)}/g, function (match, index) {
return typeof args[index] == 'undefined' ? match : args[index];
});
};
console.log('Hello {0}, your order {1} has been shipped.'.format('John', 10001));
// Output: "Hello John, your order 10001 has been shipped."
format()
method on any string with placeholders.The issue with this approach is when the placeholder count grows. It will be difficult to determine the index position and value to pass as arguments.3. Format string with variables using a template literal
One of the cleanest and most straightforward methods is to format a string using a template literal
or string interpolation
. Instead of using a single or double quoted string, we must use the backtick (' )
to encapsulate the string in this approach.
JavaScript variables can be placed within parenthesis, prefixed with the $ sign
. If this variable is placed in a JavaScript string enclosed with a backtick, then the variable will be expanded with value during runtime.
const customerName = "John";
const orderId = 10001;
console.log(`Hello ${customerName}, your order ${orderId} has been shipped.`);
// Output: "Hello John, your order 10001 has been shipped."
When string format with variables is used in the template literal, you do not need to worry about the variable index position.
Custom JavaScript string.format() method
JavaScript does not have the string.format
method like in other programming languages. However, in JavaScript, you can write a custom method.
String.prototype.format = function () {
let formattedString = this;
for (var value in arguments) {
formattedString = formattedString.replace(new RegExp("\\{" + value + "\\}", 'g'), arguments[value]);
}
return formattedString
}
console.log('Sum of {0} + {1} is {2}.'.format(5, 5, 10));
// Output: Sum of 5 + 5 is 10.
You can use this string format method on any string where you have a placeholder index
as shown below:
console.log('Sum of {0} + {1} is {2}.'.format(5, 5, 10));
// Output: Sum of 5 + 5 is 10.
String format number
Another useful method for formatting strings is to format numbers in a specific way. You can do this using the built-in toLocaleString()
method. The toLocaleString()
string method formats a number according to the user’s locale settings
.
const number = 12345.55;
console.log(number.toLocaleString());
// Output: "12,345.55"
This code will output "12,345.55"
in locales that use the comma as the decimal separator, such as the United States
and India
. This method is useful when you want to display numbers in a format that’s familiar to the user.
For example, if you want to use the French
locale, you can pass "fr-FR"
as the locale
parameter:
const number = 12345.50;
const formattedNumber = number.toLocaleString("fr-FR");
console.log(formattedNumber);
// Output: "12 345,5"
String interpolation format number
In JavaScript, you can use string interpolation
to format numbers using template literals
and the ${}
syntax. Here’s an example of how you can use string interpolation to format numbers in JavaScript:
const number = 10;
const formattedString = `The number is: ${number}`;
console.log(formattedString);
// Output: The number is: 10
String format money
To format money to a string in JavaScript, you can use the toLocaleString()
method. This method converts a number to a string with a language-sensitive
representation of the money. Here’s an example:
const money = 1234.50;
let options = { style: 'currency', currency: 'USD' }
const formattedMoney = money.toLocaleString('en-US', options);
console.log(formattedMoney);
// Output: "$1,234.50"
In this example, the toLocaleString()
method is called on the money variable with the 'en-US'
locale and options object specifying the style as 'currency'
and the currency as 'USD'
. This formats the money variable as a US dollar currency string. The formatted string is printed on the browser console.
You can replace 'USD'
with the appropriate currency code for your locale. The toLocaleString()
method also has other options you can use to customize the formatting, such as specifying the minimum and maximum number of fraction digits.
String format table structure
You can use the string methods padStart()
and padEnd()
to format an array of values in a table structure. It will pad the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the start (if the padStart()
method is used) or end (if the padEnd()
method is used) of the current string.
Let’s assume you have an array of book objects that you want to print in a table structure. Here is an example:
const books = [
{ title: 'Eloquent JavaScript', price: 29.99 },
{ title: 'JavaScript - The Good Parts', price: 19.99 }
];
const titleColumnWidth = 30;
const priceColumnWidth = 10;
const totalLength = titleColumnWidth + priceColumnWidth + 7;
books.forEach(b => {
let title = b.title.padEnd(titleColumnWidth, ' ');
let price = b.price.toString().padStart(priceColumnWidth, ' ');
console.log(`| ${title} | ${price} |`)
console.log(''.padStart(totalLength, '-'))
})
The above code will print the book object array in the following format:
| Eloquent JavaScript | 29.99 |
-----------------------------------------------
| JavaScript - The Good Parts | 19.99 |
String format frequently asked questions
What is the equivalent of String.format in JavaScript?
String.format
method, but you can use template literals or custom functions.// Using a custom function function formatString(template, ...values) { return template.replace(/{(\d+)}/g, (match, index) => values[index]); } const formattedString = formatString("Hello, {0}!, This is {1} ", "World", "JavScript"); console.log(formattedString) // Output: Hello, World!, This is JavScript
How to format currency using $ sign?
'$' sign
to represent a currency. Here is an example of format a number as a currency string using JavaScript:const amount = 1000; const options = { style: 'currency', currency: 'USD' } const formattedAmount = amount.toLocaleString('en-US', options); console.log(formattedAmount); // Output: $1,000.00
How to format string width to specific length?
Sometimes, you may need to format strings by specifying a fixed width. Here’s an example of how you can format a string with a specific width using the padStart()
method:
const text = 'JavaScript'; const formattedText = text.padStart(20, '-'); console.log(formattedText); //Output: ----------JavaScript
How to format dates using to specific locale?
custom format
. Let’s format today’s date using JavaScript.const today = new Date(); const formattedDate = today.toLocaleDateString('en-US'); console.log(formattedDate); // 6/15/2023
How to display leading zeros?
padStart()
method to achieve this. Here’s an example of formatting a number with leading zeros:const number = 12; const formattedNumber = number.toString().padStart(5, '0'); console.log(formattedNumber); // Output: 00012
How to remove letters from a string
Sometimes you may need to remove letters from a string and keep only the numeric characters. Here is an example using regular expression:
const text = 'A1B2C3'; const numbersOnly = text.replace(/\D/g, ''); console.log(numbersOnly); // Output: 123
How to format hexadecimal numbers?
If you need to format a hexadecimal number in uppercase, JavaScript provides the toUpperCase()
method. Here’s an example:
const hexNumber = 'a1b2c3'; const formattedHex = hexNumber.toUpperCase(); console.log(formattedHex); // Output: A1B2C3
How to format decimal places?
To format numbers with a specific number of decimal places, you can use the JavaScipt toFixed() method. Here’s an example:
const number = 3.14159; const formattedNumber = number.toFixed(2); console.log(formattedNumber); // Output: 3.14
How to format percentages?
'%'
symbol. Here’s an example:const percentage = 0.75; const formattedPercentage = (percentage * 100).toFixed(2) + '%'; console.log(formattedPercentage); // Output: 75.00%
How to format boolean values?
JavaScript provides the toString() method to achieve this. Here’s an example:
const value = true; const formattedValue = value.toString(); console.log(formattedValue); // Output: "true" // Format boolen to Yes or No console.log(value ? 'Yes' : 'No'); // Output: "Yes"
Are the any string format library available?
There are several JavaScript libraries available that provide advanced string formatting options. One popular library is sprintf-js, which implements the 'sprintf'
function from other programming languages.
You can include the library in your project and utilize its powerful formatting capabilities.
How do I pad a string in JavaScript?
Use String.prototype.padStart()
or String.prototype.padEnd()
methods.
const originalString = "42"; const paddedString = originalString.padStart(5, '0'); console.log(paddedString) // Output: "00042"
Conclusion
In this post, we’ve explored different JavaScript string format approaches.
Using a plus sign (+)
is the traditional approach to formatting the string. You can use the custom function or string prototype method to format the string. This approach becomes complex when the number of placeholders grows. Using string interpolation
to format the string is a simple and concise way.
Using the toLocaleString()
method, you can convert numbers and money into user locale-specific strings.
Which approach are you going to use to format the string?