Open In App

What are the Equivalent of printf/String.Format in JavaScript ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is a popular programming language that is used to create interactive and dynamic web pages. When working with JavaScript, developers often need to format strings to display data in a specific way. 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.

Approaches: To use printf or String.Format in other programming languages, you need to include the necessary library or module. However, JavaScript doesn’t have a built-in function that is equivalent to printf or String.Format. There are several approaches to achieving printf or String.Format functionality in JavaScript. Here are some approaches you can use:

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() 

Example:

Javascript




const name = 'Geek';
const age = 14;
  
console.log('My name is ' + name 
    + ' and I am ' + age + ' years old.');


Output

My name is Geek and I am 14 years old.

2. Using document.write() Method: Another method for displaying integer and string values in JavaScript is document.write(). Unlike console.log(), which prints values to the console, document.write() writes the values directly to the HTML document, or Document Object Model (DOM).

Syntax:

document.write()

Example:

Javascript




const name = 'John';
const age = 30;
  
document.write(`My name is ${name} and I am ${age} years old.`);


Output:

output

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. The code for this function might look like this:

String.prototype.format = function() {
      const args = arguments;
      return this.replace(/{(\d+)}/g, function(match, number) { 
        return typeof args[number] != 'undefined'
              ? args[number]
              : match;
      });
};

To use the format function, we can specify the indexes of the placeholders. We want to replace it with new string values. These string values can be passed as arguments to the format method. The index specifies the position in the string where the specified string will be replaced. For example:

const name = 'Alice';
const age = 25;
const message = 
'My name is {0} and I am {1} years old.'.format(name, age);

// Output: "My name is Alice and I am 25 years old."
console.log(message); 

In this example, we have specified the indexes {0} and {1} where the string values need to be replaced. These new string values are placed as arguments to the format method. The first argument “Alice” is placed at index {0}, and the second argument 25 is placed at index {1}. The resulting string is assigned to the message variable and printed to the console using console.log(). The placeholders are replaced with the corresponding string values, resulting in the string “My name is Alice and I am 25 years old.”.

Example:

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);


Output

Hello John, welcome to New York.

4. 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:

(`${}`)

Example :

Javascript




const name = 'John';
const age = 30;
  
console.log(`My name is ${name} and I am ${age} years old.`);


Output

My name is John and I am 30 years old.

5. Using the replace() method: You can use the replace method to replace placeholders in a string with variable values.

Syntax:

str.replace(searchValue, replaceValue)

Example:

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);


Output

Hello John, welcome to India.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads