JavaScript equivalent to printf/String.Format
Are you wondering how to format strings in JavaScript similar to printf in C or String.Format in C#? JavaScript offers several ways to embed variables and format strings dynamically—let’s explore how!
In JavaScript, there isn't a built-in printf or String.Format function like in some other languages, but you can still achieve the same string formatting in a few easy ways.
Here are some commonly used alternatives:
- Template Literals (ES6 and later):
- This is the most modern and readable way to format strings.
const name = "Alice";
const age = 30;
console.log(`My name is ${name} and I am ${age} years old.`);
- Clean syntax using backticks (`)
- You can embed expressions directly
String Concatenation:
A traditional method but can get messy with longer strings.
const message = "Hello, " + name + "! You are " + age + " years old.";
String.prototype.replace() or format() polyfills:
You can write your own format-style function or use libraries like Lodash.
function format(str, ...args) {
return str.replace(/{(d+)}/g, (match, index) => args[index] || "");
}
console.log(format("My name is {0} and I am {1} years old.", "Bob", 25));
Using console.log() with placeholders:
Works similarly to printf.
console.log("Hello %s, you are %d years old.", "John", 28);
Final Thoughts:
If you're working in modern JavaScript, template literals are the easiest and most powerful way to handle string formatting. But for legacy or more complex formatting, custom functions or libraries can help mimic String.Format.