Printf or String.Format in JavaScript
Last Updated :
30 Nov, 2024
The printf function and the String.Format() methods are two popular string formatting tools in other programming languages, but JavaScript does not have a built-in equivalent. However, there are several approaches to achieving the same functionality in JavaScript.
Modern way to print string.
JavaScript
let name = "GeeksforGeeks";
let greeting = `Hello, and welcome to ${name}`;
console.log(greeting);
OutputHello, and welcome to GeeksforGeeks
1. Using console.log() Method
JavaScript provides the console.log() method for printing the value of variables and expressions to the console. This method is often used for debugging and testing purposes, but it can also be used for printing strings and integers in a specific format, similar to the printf() function in other programming languages.
Syntax
console.log()
JavaScript
const name = 'Geek';
const age = 14;
console.log('My name is ' + name
+ ' and I am ' + age + ' years old.');
OutputMy name is Geek and I am 14 years old.
2. Using Template Literals
In JavaScript, you can use template literals to achieve similar functionality. Template literals allow you to embed expressions inside a string by using ${} syntax.
Syntax
(`${}`)
JavaScript
const name = 'John';
const age = 30;
console.log(`My name is ${name} and I am ${age} years old.`);
OutputMy name is John and I am 30 years old.
3. Using the String.format Method
Although JavaScript doesn't have a built-in String.Format method, you can create one yourself using the prototype property of the String object.
Syntax: To create a custom prototype function in JavaScript, we can define a new method called format on the String prototype. This method will take a string and replace any placeholders in the form of {n} with the corresponding argument passed to the method.
String.prototype.format = function() {
const args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
JavaScript
String.prototype.format = function () {
const args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
const str = 'Hello {0}, welcome to {1}.';
const name = 'John';
const city = 'New York';
const formattedStr = str.format(name, city);
console.log(formattedStr);
OutputHello John, welcome to New York.
4. Using the replace() Method
You can use the replace method to replace placeholders in a string with variable values.
Syntax
str.replace(searchValue, replaceValue)
JavaScript
const str = 'Hello {0}, welcome to {1}.';
const name = 'John';
const city = 'India';
const formattedStr = str.replace('{0}', name).replace('{1}', city);
console.log(formattedStr);
OutputHello John, welcome to India.
Similar Reads
JavaScript String Formatting 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 st
5 min read
How to Print a String in JavaScript ? In JavaScript, printing a string means displaying the contents of a string variable or literal to the console, webpage, or any other output medium. Strings are a fundamental data type in JavaScript, representing sequences of characters enclosed within single ('') or double ("") quotes. Table of Cont
2 min read
How to Pretty Print JSON String in JavaScript? To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level.Pretty printing JSON adds line breaks and spaces for readability.It is c
3 min read
How to Create JSON String in JavaScript? JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read
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
JavaScript String Operators JavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read