In this tutorial, we will delve into the concept of string formatting in JavaScript. To begin, we will explore the fundamentals of JavaScript strings.
JavaScript string
In JavaScript, a string is a sequence of characters enclosed in single or double quotation marks. The characters in a string are indexed starting from 0 for the first character, 1 for the second character, and so forth.
String formatting
The fundamental idea behind string formatting involves embedding variables within a string, which are referred to as placeholders.
There are many methods which are utilized to format a string:
- ${} within backticks
- Concatenation
- String interpolation
- Custom function
Each technique will be comprehensively explained through practical examples.
Utilizing ${} within Backticks
To format a string, we can utilize the ${} syntax enclosed within backticks. The backtick character is denoted as ( ).
Demo 1:
Let's define a pair of string variables called topic1 and topic2. Next, we will assign values to both of these strings. To display a formatted string, we will employ and ${}.
Code:
let subject1 = "Core Java";
let subject2 = "Advanced Java";
let str = `Learn ${subject1} and ${subject2} from our tutorial.`;
console.log(str);
Output:
Learn Core Java and Advanced Java from our tutorial.
Demo 2:
Let's create two string variables called mathGrades and englishGrades. Next, we will concatenate the strings and assign the result to a new string named total. To format a string, we will use string interpolation, ${}, and the conditional ternary operator.
Code:
const mathsMarks = 90;
const englishMarks = 115;
const total = mathsMarks + englishMarks;
const displayMarks = `Your total marks are ${total}. ${total > 150 ? `Congrats! You are eligible to get admission to the school.` : `Sorry! You are not eligible to get admission to the school.`}`
console.log(displayMarks);
let student = false;
console.log(`You are ${student == true ? "a student." : "not a student."}`);
Output:
Your total marks are 205. Congrats! You are eligible to get admission to the school.
You are not a student.
Demo 3:
A variable called "student" will be initialized as a string with a Boolean value set to false. Subsequently, a string will be formatted based on this condition.
Code:
let student = false;
console.log(`You are ${student == true ? "a student." : "not a student."}`);
Output:
You are not a student.
Utilizing concatenation (+ operator)
Concatenation is a technique used for formatting a string by combining two or more strings together.
Demo 1:
Three strings, namely s1, s2, and s3, will be defined, and their respective values will be assigned. The concatenation operator will be used to combine s1 and s2, and the result will be stored in a new string variable.
Code:
let s1 = "Welcome "
let s2 = "to "
let s3 = "JTP!"
let s4 = s1 + s2 +s3
console.log(s4);
Output:
Welcome to JTP!
Demo 2:
In this example, we will demonstrate how to format a string using the concatenation operator in combination with the ternary operator. To begin, we will define a string variable called "age" and assign a value to it. Afterwards, we will output a new string incorporating this variable.
Code:
const age = 15;
const display = ("You are " + (age > 17 ? "eligible to vote" : "not eligible to vote") + " this time.");
console.log(display);
Output:
You are not eligible to vote this time.
Demo 3:
Declare two strings, 'number1' and 'number2'. Calculate the variance between these strings and assign the result to a new string called 'difference'. Display the formatted string output.
Code:
const number1 = 45;
const number2 = 20;
const difference = number1 - number2;
console.log('The difference between 45 and 20 is ' + difference);
Output:
The difference between 45 and 20 is 25
Utilizing String interpolation
String interpolation is a technique employed to format strings by embedding variables, mathematical operations, and function invocations within them.
Demo 1:
Declare four strings: firstName, lastName, studentName, and message. Create a new string named formatted_message and assign it the updated value of the message.
Code:
const firstName = 'Ajeet ';
const lastName = 'Kumar';
const studentName = firstName + lastName;
const message = 'Welcome {studentName}, submit your assignment.';
const formatted_message =
message.replace('{studentName}', studentName);
console.log(formatted_message);
Output:
Welcome Ajeet Kumar, submit your assignment.
Demo 2:
Declare two string variables with the names employeeName and message. Create a new string variable named formatted_message and assign it the updated value of the message string.
Code:
const employeeName = 'Anjali';
const message = 'Hello {employeeName}, show your work.';
const formatted_message =
message.replace('{employeeName}', employeeName);
console.log(formatted_message);
Output:
Hello Anjali, show your work.
Utilizing custom function
The custom function will be employed for formatting a string.
Demo:
A personalized function will be generated, followed by the output of the formatted string.
Code:
String.prototype.format = function () {
var arr = arguments;
return this.replace(/{([0-9]+)}/g, function (match, index) {
return typeof arr[index] == 'undefined' ? match : arr[index];
});
};
let employeeName = "Shrishti"
let university = "Chandigarh University"
let message = "Congratulations, {0} from {1}! Welcome to our tutorial.".format(employeeName, university);
console.log(message);
Output:
Congratulations, Shrishti from Chandigarh University! Welcome to our tutorial.
Conclusion:
This article has provided a thorough exploration of string formatting in JavaScript. Through practical illustrations, we have delved into different approaches, empowering us to implement these strategies in upcoming endeavors.