JavaScript String Formatting
Last Updated :
19 Jul, 2023
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
- 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:
Javascript
let str1 = "Welcome "
let str2 = "to "
let str3 = "GeeksforGeeks"
let str4 = str1 + str2 +str3
console.log(str4)
|
Output
Welcome to GeeksforGeeks
- 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:
Javascript
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
String interpolation is a great programming language feature that allows injecting variables, function calls, and arithmetic expressions directly into a string.
Example:
Javascript
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.
Share your thoughts in the comments
Please Login to comment...