What you'll learn
Text appears everywhere: names, messages, URLs, form input, and API data. JavaScript strings provide a focused toolkit for inspecting and transforming it.
Creating strings and immutability
Single quotes, double quotes, and backticks create strings. Pick a consistent quote style; use backticks when you need interpolation or multiline text.
const single = 'Hello';
const double = "JavaScript";
const escaped = "She said, \"Hello!\"";
const multiline = `First line
Second line`;
console.log(single + " " + double);
console.log(escaped);Strings are immutable: methods return new strings. They never edit the original value.
Indexing, length, and Unicode
const word = "JavaScript";
console.log(word.length);
console.log(word[0]);
console.log(word.at(-1));Indexes begin at zero. at(-1) reads from the end. JavaScript's historical length counts UTF-16 code units, so some emoji count as two.
const emoji = "🚀";
console.log(emoji.length);
console.log([...emoji].length);Note
Essential string methods
| Method | Purpose | Example result |
|---|---|---|
trim() | Remove surrounding whitespace | " hi " → "hi" |
toLowerCase() | Normalize case | "JS" → "js" |
includes() | Test for text | "JavaScript".includes("Script") |
replaceAll() | Replace every match | "a-a" → "a a" |
split() | Create an array of pieces | "a,b" → ["a","b"] |
Searching and extracting
const title = "Learn modern JavaScript";
console.log(title.includes("modern"));
console.log(title.startsWith("Learn"));
console.log(title.indexOf("Java"));
console.log(title.slice(6, 12));
console.log(title.slice(-10));Watch out
slice(start, end) excludes the end index. If no match exists, indexOf returns -1; includes is clearer when you only need yes/no.Template literals and interpolation
Backticks allow expressions inside $${ ... }. JavaScript evaluates each expression and inserts its result.
const learner = "Nour";
const completed = 4;
const total = 8;
const message = `${learner} completed ${completed}/${total} lessons (${completed / total * 100}%).`;
console.log(message);Key idea
A practical normalization pipeline
Real input is messy. Chain small transformations so each step is visible:
const rawTag = " JavaScript Basics ";
const slug = rawTag
.trim()
.toLowerCase()
.replaceAll(" ", "-");
console.log(slug);Method chaining works because each method returns the next string value. Break long chains onto separate lines for readability.
Recap & quick check
Key takeaways
- Strings are immutable sequences represented with UTF-16.
- Index from zero and use at(-1) for the last element.
- Use trim, case conversion, includes, slice, replace, and split for common transformations.
- Template literals support readable interpolation and multiline text.
- Normalize external text before comparing or storing it.
Quick check
1. What does 'JavaScript'.at(-1) return?
2. Do string methods modify the original string?
3. Which syntax interpolates an expression?
4. What does slice(1, 4) include?