Tutorials Tonight
Follow Us

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. String Formatting in JavaScript
    1. Format String Using Backticks
    2. Format String Using Plus Operator
    3. String format using a custom function
  3. Javascript String Format Example
  4. Conclusion

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.

Many languages have a built-in string method to format strings, 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.

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.


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

Stay Ahead, Learn More

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

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

// 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
// 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

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


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 string in javascript. We have discussed 3 different ways for JavaScript string format.

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

No matter if you’re looking for this explanation to do your homework or to complete some kind of your working task, we hope that it was clear enough to comprehend. There’s another way of searching for solutions for your tasks. You can order JavaScript assignment help and use their knowledge to deal with your working load if you got stuck and there’s nobody to help you out. Many junior programmers find such assistance efficient and get more use of it than from reading Quora, Reddit, or StackOverflow. Any questions deserve to get a full explanation, especially if you’re a newbie.