Skip to content

Strings

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.

// String creation
const name1 = "Alice";
const name2 = 'Bob';
const greeting = `Hello, ${name1}!`; // template literal
// String properties
console.log(name1.length); // 5
// Common methods
const 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")); // true
console.log(sentence.startsWith("Hello")); // true
console.log(sentence.endsWith("World")); // true
console.log(sentence.indexOf("World")); // 6
console.log(sentence.slice(0, 5)); // "Hello"
console.log(sentence.substring(6)); // "World"
console.log(sentence.replace("World", "JS")); // "Hello JS"
// Template literals
const name = "Alice";
const age = 25;
const bio = `
Name: ${name}
Age: ${age}
Status: ${age >= 18 ? "Adult" : "Minor"}
`;
// String repeat and pad
console.log("*".repeat(5)); // "*****"
console.log("5".padStart(3, "0")); // "005"
console.log("5".padEnd(3, "0")); // "500"

Trying to mutate strings directly:

// BAD - strings are immutable
let text = "hello";
text[0] = "H"; // Doesn't work! text is still "hello"
// GOOD - create new string
text = "H" + text.slice(1); // "Hello"
// or
text = text.replace("h", "H"); // "Hello"

Fix: Always create new strings instead of trying to modify existing ones.

  1. How do you combine (concatenate) two strings?

    Answer`str1 + str2` or use template literal: `` `${str1}${str2}` ``
  2. What does "hello".split("") return?

    Answer`["h", "e", "l", "l", "o"]` - splits into individual characters
  3. Convert ” HELLO ” to “hello” (trimmed and lowercase).

    Answer`" HELLO ".trim().toLowerCase()`