Open In App

JavaScript String Formatting

JavaScript Strings are used to print an array of characters and are a primitive data type. While creating and printing strings we sometimes want to add values from other variables or concatenate multiple strings to create a single string. To solve this issue we use formatting. JavaScript provides various inbuilt methods to format a string.

In this article, we will discuss methods to format a string. The formatted string can contain a combination of two or more strings and can even store different variable values combined with an original string



These are the methods by which we format a string:

Method 1: Using concatenation

Example:






let str1 = "Welcome "
let str2 = "to "
let str3 = "GeeksforGeeks"
 
let str4 = str1 + str2 +str3
 
console.log(str4)

Output
Welcome to GeeksforGeeks

Method 2: Using backticks

Example:




let str1 = "DSA";
let str2 = "Web Development";
 
let str3 = `Use GeeksforGeeks to learn ${str1} and ${str2}`;
             
console.log(str3);

Output
Use GeeksforGeeks to learn DSA and Web Development

Method 3: Using String interpolation

String interpolation is a great programming language feature that allows injecting variables, function calls, and arithmetic expressions directly into a string. 

Example:




const name = 'Geeksforgeeks';
const message = 'Welcome to {name}.';
const formattedMessage =
      message.replace('{name}', name);
console.log(formattedMessage);

Output
Welcome to Geeksforgeeks.

We have a complete list of JavaScript string methods, to check those please go through this JavaScript String reference article.


Article Tags :