Tutorials Tonight
Follow Us

JavaScript String Format


In this article, you are going to learn what is string formating or string interpolation in JavaScript, different ways to format a string in JavaScript, creating a function to format a string, and how to use string formatting in JavaScript.

String Formatting

String formatting is the process of inserting variables into a string. In modern languages generally, it is done by using the {} brackets. It is also called string interpolation.

Some of the languages have a built-in string method to format string, but not all languages have it.

Another very famous approach to string formatting is concatenation. It is a process of inserting variables into a string. In modern languages generally, it is done by using the + operator.

string formatting in javascript

From the above image, you can see that the variables are inserted into the string and called placeholders. The placeholders get replaced with the values of the variables and we can see that the string is formatted.


String Formatting in JavaScript

In javascript, there is no built-in string formatting function. But there are other ways to format a string in javascript which we are going to learn in this article.

We are going to see the following 3 ways to format a string in javascript.

  1. Using {} brackets within backticks ``
  2. Using + operator
  3. By creating a format function

1. Format String Using Backticks

Formatting string in javascript is best done by the use of backticks (``) and the variables are inserted within the backticks wrapped in curly braces ({}) preceded by a dollar sign ($).

Example: `Hello ${name}`

These variables are called placeholders within the string which is replaced with the values of the variables.

Example

let name = "John";
let age = 30;
let food = "pizza";

// String formating using backticks
let sentence = `${name} is ${age} years old and likes ${food}`;

console.log(sentence); // John is 30 years old and likes pizza

You can run and see the output of the above code all the placeholders are replaced with the values of the variables.

string formatting in javascript

Possible mistake: Make sure that you are using backticks (`) and not single quotes (') or double quotes (").


Within these backticks, any javascript expression is valid and it will be evaluated and replaced with the value of the expression.

You can use variables, functions, and any javascript expression within the backticks.

Example

// arithmetic expression
var sum = `${2 + 2}`;
console.log(sum); // 4

// function call
function fullName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}
console.log(`Full name is ${fullName("John", "Smith")}`); // John Smith

// Ternary operator
let age = 30;
let message = `${age >= 18 ? "Adult" : "Child"}`;
console.log(message); // Adult

2. Format String Using Plus Operator

Another way to format a string is by using the + operator. This is done by concatenating the string with the variables.

Example: 'Hello' + name + '!'

This replaces the variable with the value and concatenates it with the string.

Example

let name = "John";
let age = 30;
let food = "pizza";

// String formating using plus operator
let sentence = name + ' is ' + age + ' years old and likes ' + food;

console.log(sentence); // John is 30 years old and likes pizza

Even with this method, you can use variables and functions within the string but it is not recommended because it is not as readable as the backticks and if not done correctly it can lead to unexpected results.

Example

let age = 30;
console.log('You are ' + age > 18 ? 'Adult' : 'Child');

// unexpected result
console.log('Sum of 2 + 2 is ' + 2 + 2);

// correct way
// use small brackets
console.log('Sum of 2 + 2 is ' + (2 + 2));

3. Javascript String Format Function

Other programming languages have a built-in function to format a string. One such programming language is python.

In python, there is a method called format() which is used to format a string. The method accepts a list of variables and replaces the placeholders with the values of the variables. The placeholders contain integers starting from 0 in curly braces ({}) where 0 denotes the first placeholder and 1 denotes the second placeholder and so on.

Example: 'Hello {0}. You like {1}'.format(name, fruit)

We are going to create the same method in javascript.

Example: String.format function

String.prototype.format = function () {
  // store arguments in an array
  var args = arguments;
  // use replace to iterate over the string
  // select the match and check if related argument is present
  // if yes, replace the match with the argument
  return this.replace(/{([0-9]+)}/g, function (match, index) {
    // check if the argument is present
    return typeof args[index] == 'undefined' ? match : args[index];
  });
};

console.log('{0} is {1} years old and likes {2}'.format('John', 30, 'pizza'));

The above method is made to be part of the string prototype so that it can be used on any string object. You can also use it on any variable which is a string.


Javascript String Format Example

Below is an example of how to use the above methods.

Example: Assign value

// assigning value
var marks = 65;
var status = `John => ${marks >= 60 ? "Pass" : "Fail"}`;
console.log(status); // John => Pass

Example: JavaScript expression

// JavaScript expression
var numbers = [13, 2, 32, 54, 5];
var biggest = `The biggest number is ${Math.max(...numbers)}`;
console.log(biggest); // The biggest number is 54

Similarly, you can use the above mensioned methods on any string object to format it.


Conclusions

In web development, we continuously need to format strings in javascript. We have discussed 3 different ways to format string in this article.

By far the best way is to use backticks to format the string.