string formatter javascript OR JavaScript String Format or Interpolation

string formatter javascript is the process of inserting variables into a string. Using {} brackets within backticks “, Using + operator and By creating a format function.

string formatter javascript

js format string

Simple String.format() in javascript

String.prototype.format = function() {
  a = this;
  for (k in arguments) {
    a = a.replace("{" + k + "}", arguments[k])
  }
  return a
}

Usage of js format string

console.log("Welcome, {0}!".format("Pakainfo"))

1. Format String Using Backticks

javascript format string

let name = "Rakesh";
let age = 30;
let lunch = "dabeli";

// String formating using backticks
let data_content = `${name} is ${age} years old and favourites ${lunch}`;

console.log(data_content); // Rakesh is 30 years old and favourites dabeli

Format String Using Plus Operator

let name = "Rakesh";
let age = 30;
let lunch = "dabeli";

// String formating using plus operator
let data_content = name + ' is ' + age + ' years old and favourites ' + lunch;

console.log(data_content); // Rakesh is 30 years old and favourites dabeli

Don’t Miss : Javascript Converting Strings To Number Example

Javascript String Format Example

Example: Assign value

// assigning value
var ranks = 65;
var status = `Rakesh => ${ranks >= 60 ? "Pass" : "Fail"}`;
console.log(status); // Rakesh => 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

I hope you get an idea about javascript format string.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment