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:
- Using concatenation Method
- Using backticks
- Using String interpolation
Method 1: Using concatenation
- Declare multiple strings and store their value in a variable
- Use the concatenation operator to combine the values and store it in a different string
- Print the concatenated string
Example:
let str1 = "Welcome "
let str2 = "to "
let str3 = "GeeksforGeeks"
let str4 = str1 + str2 +str3 console.log(str4) |
Welcome to GeeksforGeeks
Method 2: Using backticks
- Declare multiple strings and store their value in a variable
- Use the “ and ${} to format the string and use the value of variables
- Print the concatenated string
Example:
let str1 = "DSA" ;
let str2 = "Web Development" ;
let str3 = `Use GeeksforGeeks to learn ${str1} and ${str2}`; console.log(str3); |
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); |
Welcome to Geeksforgeeks.
We have a complete list of JavaScript string methods, to check those please go through this JavaScript String reference article.