A JavaScript string consists of any number of characters enclosed within quotation marks.
const fullName = 'Jane Smith';
Both single and double quotes can be used to define strings, offering flexibility in how strings are written.
const primaryVehicle = 'Toyota Corolla';
const secondaryVehicle = "BMW X5";
Quotes Inside Quotes
You can include quotes within a string as long as the inner quotes do not match the ones used to define the string itself.
const message1 = 'It\'s fine';
const message2 = "She said 'Hello'";
const message3 = 'He replied, "Good morning"';
Escape Characters
Since strings need to be enclosed in quotes, JavaScript may misinterpret the content if quotes are missing or mismatched.
let phrase = "We are the legendary "Guardians" hailing from the frozen lands.";
The above statement will give an error because of the unescaped double quotes.
To fix this, you can use the backslash escape character (\
). This instructs JavaScript to treat special characters like quotes as regular characters within the string.
let phrase = "We are the legendary \"Guardians\" hailing from the frozen lands.";
The sequence \'
lets you include a single quote inside a string, treating it as a regular character instead of the string delimiter.
const message = 'It\'s a nice day.';
Note: The six escape sequences mentioned earlier were initially developed for controlling typewriters, teletypes, and fax machines. Their relevance in modern web development, especially in HTML, is minimal as they were designed for a different era of technology.
Template Strings
Template strings, introduced in ES6 (JavaScript 2016), allow you to create strings enclosed in backticks (`
). This feature enables the use of multi-line strings without requiring any concatenation or escape characters for line breaks.
let text = `Swiftly,
the dark wolf
leaps across
the silent valley.`;
Note: Template literals are not supported in Internet Explorer. Therefore, developers should use traditional string concatenation methods or other workarounds when working with older browsers like Internet Explorer.
Interpolation
Template literals offer a simple way to embed variables and expressions directly within a string.
This feature is known as string interpolation.
The syntax for this is:
${...}
Variable Substitutions
Template literals allow you to seamlessly insert variables into strings.
let userName = "Alice";
let userLastName = "Smith";
let greeting = `Hello ${userName} ${userLastName}, welcome back!`;
console.log(greeting); //Hello Alice Smith, welcome back!
String interpolation refers to the automatic insertion of variable values into a string.
Expression Substitution
Template literals enable the inclusion of expressions directly within strings.
let mealPrice = 30;
let serviceCharge = 0.10;
let billTotal = `Final Bill: ${(mealPrice * (1 + serviceCharge)).toFixed(2)}`;
console.log(billTotal); // Final Bill: 33.00