
Introduction of Strings
A string in JavaScript is a sequence of characters used to represent text. Strings are enclosed in single quotes ('), double quotes ("), or backticks (`). They are immutable, meaning once a string is created, its content cannot be changed (though you can assign a new string to the same variable).
Defining Strings
1. Single quotes (')let singleQuoteString = 'Hello, World!';let doubleQuoteString = "Hello, World!";let backtickString = `Hello, Template Literals!`;Template Literals
Template literals are a modern way of working with strings in JavaScript, introduced in ES6. They are enclosed by backticks (`) and allow embedding expressions using the syntax ${expression}. They also support multi-line strings without needing escape characters.
const name = 'Alice';
const age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);
// Output: My name is Alice and I am 25 years old.const multiLine = This is a
multi-line
string.;
console.log(multiLine);Escape Sequences
Escape sequences in JavaScript are used to include special characters within a string. They begin with a backslash (\), followed by a character that represents the desired special character.
Example of Escape Sequence
let singleQuote = 'It\'s a sunny day!'; // Escaping a single quote
let doubleQuote = "She said, \"Hello!\""; // Escaping a double quote
let newLine = "Hello\nWorld!"; // Newline
let tab = "Name\tAge"; // Tab
console.log(singleQuote); // It's a sunny day!
console.log(doubleQuote); // She said, "Hello!"
console.log(newLine);
// Output:
// Hello
// World!
console.log(tab); // Name Age