Strings
Strings
Section titled βStringsβWhat it means
Section titled βWhat it meansβStrings represent text. JavaScript strings are immutable (canβt be changed, only replaced) and support both single quotes, double quotes, and template literals (backticks) for interpolation.
Examples
Section titled βExamplesβ// String creationconst name1 = "Alice";const name2 = 'Bob';const greeting = `Hello, ${name1}!`; // template literal
// String propertiesconsole.log(name1.length); // 5
// Common methodsconst text = " JavaScript ";console.log(text.trim()); // "JavaScript"console.log(text.toLowerCase()); // " javascript "console.log(text.toUpperCase()); // " JAVASCRIPT "
const sentence = "Hello World";console.log(sentence.split(" ")); // ["Hello", "World"]console.log(sentence.includes("World")); // trueconsole.log(sentence.startsWith("Hello")); // trueconsole.log(sentence.endsWith("World")); // trueconsole.log(sentence.indexOf("World")); // 6console.log(sentence.slice(0, 5)); // "Hello"console.log(sentence.substring(6)); // "World"console.log(sentence.replace("World", "JS")); // "Hello JS"
// Template literalsconst name = "Alice";const age = 25;const bio = ` Name: ${name} Age: ${age} Status: ${age >= 18 ? "Adult" : "Minor"}`;
// String repeat and padconsole.log("*".repeat(5)); // "*****"console.log("5".padStart(3, "0")); // "005"console.log("5".padEnd(3, "0")); // "500"Common mistake
Section titled βCommon mistakeβTrying to mutate strings directly:
// BAD - strings are immutablelet text = "hello";text[0] = "H"; // Doesn't work! text is still "hello"
// GOOD - create new stringtext = "H" + text.slice(1); // "Hello"// ortext = text.replace("h", "H"); // "Hello"Fix: Always create new strings instead of trying to modify existing ones.
Quick practice
Section titled βQuick practiceβ-
How do you combine (concatenate) two strings?
Answer
`str1 + str2` or use template literal: `` `${str1}${str2}` `` -
What does
"hello".split("")return?Answer
`["h", "e", "l", "l", "o"]` - splits into individual characters -
Convert β HELLO β to βhelloβ (trimmed and lowercase).
Answer
`" HELLO ".trim().toLowerCase()`