JS Strings
let text = "value";
let text = 'value';
let text = `template ${expression}`;
text.length;
Creating Strings
Strings can be created with single quotes, double quotes, or backticks, and all three behave the same for basic text, the choice is largely a matter of consistency and, for backticks, added features.
उदाहरण: Creating Strings
// Declare the variable `a`, set to 'Single quotes'
// Declare the variable `a`, set to 'Single quotes'
let a = 'Single quotes';
// Declare the variable `b`, set to "Double quotes"
// Declare the variable `b`, set to "Double quotes"
let b = "Double quotes";
// Declare the variable `c`, set to `Backticks`
// Declare the variable `c`, set to `Backticks`
let c = `Backticks`;
// Print `a, b, c` to the console
// Print `a, b, c` to the console
console.log(a, b, c);
Template Literals
Template literals, written with backticks, let you embed variables and expressions directly inside a string using ${expression}, avoiding the need to join text together with the + operator.
उदाहरण: Template Literals
// Declare the constant `name`, set to "Maya"
// Declare the constant `name`, set to "Maya"
const name = "Maya";
// Declare the constant `age`, set to `25`
// Declare the constant `age`, set to `25`
const age = 25;
// Print `${name} is ${age} years old.` to the console
// Print `${name} is ${age} years old.` to the console
console.log(`${name} is ${age} years old.`);
String Length
Every string has a length property that returns the number of characters it contains, counting letters, numbers, spaces, and punctuation all equally.
उदाहरण: String Length
const message = "Hello!";
console.log(message.length);
Escape Characters
Escape characters, starting with a backslash, let you include special characters inside a string, like \n for a new line, \t for a tab, or \' to include a quote that would otherwise end the string early.
उदाहरण: Escape Characters
console.log("Line one\nLine two");
console.log("She said \"hello\"");
Comparing Strings
Strings can be compared with equality and relational operators, comparing them character by character based on their character codes, with strict equality === checking both value and type together.
उदाहरण: Comparing Strings
// Print "Apple" === "apple" to the console
// Print "Apple" === "apple" to the console
console.log("Apple" === "apple");
// Print "apple" === "apple" to the console
// Print "apple" === "apple" to the console
console.log("apple" === "apple");
// Print "apple" < "banana" to the console
// Print "apple" < "banana" to the console
console.log("apple" < "banana");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: