JavaScript String Format - in 3 Ways


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

    Table Of Contents

  1. String formatting
  2. Quick Solution
  3. String Formatting in JavaScript
    1. Using Backticks
    2. Using Plus Operator
    3. Using a custom function
  4. String Formatting Example
  5. Conclusion

1. String Formatting

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

Many languages have a built-in string method to format strings, but not all languages have it.

Another famous approach for string formatting is concatenation. It is a process of joining two or more strings together. It is done by using the + operator.

javascript string format
JavaScript Format String

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.


2. Javascript Format String (Quick Solution)

For your quick reference, here is the code for string formatting in javascript in 3 different ways.

Example

let name = "John";
let age = 25;
let city = "New York";

// 1. Using backticks
let str1 = `My name is ${name}. I am ${age} years old. I live in ${city}.`;
console.log(str1);

// 2. Using + operator
let str2 = "My name is " + name + ". I am " + age + " years old. I live in " + city + ".";
console.log(str2);

// 3. Using a custom function
String.prototype.format = function() {
  let formatted = this;
  for (let i = 0; i < arguments.length; i++) {
    let regexp = new RegExp('\\{'+i+'\\}', 'gi');
    formatted = formatted.replace(regexp, arguments[i]);
  }
  return formatted;
};
let formatted = "Hello {0}! Welcome to {1}.".format("John", "New York");
console.log(formatted);

For detail explanation, read the article below.


3. String Formatting in JavaScript

In javascript, there is no built-in string formatting function. But there are other ways to format a string.

Here we are going to look at the 3 different methods to format a string in javascript.

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

3.1. Format String Using Backticks

Best way to format a string in javascript is by using backticks ``.

To format string backticks wraps the string and the variables are inserted within the backticks wrapped in curly braces {} preceded by a dollar sign $.

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

Example

// format string javascript
let name = "John";
let age = 30;
let food = "pizza";

// String formatting 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.

format string javascript backticks
format string 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(fName, lName) {
  return `${fName} ${lName}`;
}
console.log(`My full name is ${fullName("John", "Smith")}`);
// My full name is John Smith

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

Stay Ahead, Learn More

3.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

// javascript format string

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

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

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

You can also use javaScript expressions and function calls within the string but you need to be careful because it can lead to unexpected results, also this is not recommended because it is not as readable as the backticks.

Example

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

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

// correct way
// using parenthesis
console.log('Sum of 2 + 2 is ' + (2 + 2));

3.3. Custom function for String Formatting

As we mensioned earlier that some languages have built-in function to format a string. Like in Python.

Here we are going to create a string method (using prototype) that will be called on string and replace the placeholders with the values of the variables.

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

Example: String.format function

// JS format string
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 the 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.


String Formatting Examples

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.


Frequency Asked Questions

  1. What is ${} in JavaScript?

    ${} is a placeholder in JavaScript. It is used to insert the value of a variable or an expression in a string. They are used in template literals ``.

  2. How to format a string in JavaScript?

    As discussed in the article, there are 3 ways to format a string in JavaScript. 1. Using plus operator, 2. Using backticks, 3. Using custom function.

  3. What is the format of string template in JavaScript?

    The format of string template in JavaScript is `${variable}` or `${expression}`. It is used to insert the value of a variable or an expression in a string.


Conclusions

In web development, we continuously need to format string in javascript. We have discussed 3 different ways for js string format.

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