JavaScript Notes
Complete JavaScript string methods guide: toUpperCase, toLowerCase, trim, slice, split, join, padStart, repeat, at(), and all essential methods with examples and output blocks.
How String Methods Work
Every string in JavaScript has access to a set of built-in methods from String.prototype. They all share one important rule:
String methods never modify the original string. They always return a new string (or other value). Strings are immutable.
"hello".toUpperCase()
↓
Returns a NEW string: "HELLO"
Original "hello" is untouched.Case Conversion
toUpperCase() and toLowerCase()
const message = "Hello, JavaScript World!";
console.log(message.toUpperCase());
console.log(message.toLowerCase());
console.log(message); // original unchangedHELLO, JAVASCRIPT WORLD! hello, javascript world! Hello, JavaScript World!
Practical: Case-insensitive comparison
const userInput = " JaVaScRiPt ";
const keyword = "javascript";
const isMatch = userInput.trim().toLowerCase() === keyword;
console.log(isMatch);true
Whitespace Removal
trim(), trimStart(), trimEnd()
const raw = " Hello, World! ";
console.log(`|${raw.trim()}|`);
console.log(`|${raw.trimStart()}|`);
console.log(`|${raw.trimEnd()}|`);|Hello, World!| |Hello, World! | | Hello, World!|
Visual:
" Hello, World! "
^^^ ^^^
trimStart() trimEnd()
removes these removes these
trim() removes BOTH sidesString Extraction — slice()
slice(start, end) extracts a portion of the string. Does not include the character at end index.
const str = "JavaScript";
// 0123456789
console.log(str.slice(0, 4)); // from 0 up to (not including) 4
console.log(str.slice(4)); // from index 4 to end
console.log(str.slice(-6)); // last 6 characters
console.log(str.slice(0, -6)); // all except last 6
console.log(str.slice(4, 6)); // chars at index 4 and 5Java Script Script Java Sc
"JavaScript"
0123456789
slice(0, 4) → J a v a
0 1 2 3 (stops before index 4)
slice(-6) → S c r i p t
4 5 6 7 8 9 (last 6 characters)substring() vs slice()
const text = "Hello World";
// Both work the same for positive indices
console.log(text.slice(0, 5));
console.log(text.substring(0, 5));
// Difference: negative indices
console.log(text.slice(-5)); // "World" — negative works
console.log(text.substring(-5)); // "Hello World" — treats -5 as 0Hello Hello World Hello World
| Feature | slice(start, end) | substring(start, end) |
|---|---|---|
| Negative indices | ✅ Supported (counts from end) | ❌ Treated as 0 |
| Auto-swap args if start > end | ❌ Returns empty | ✅ Swaps them |
| Recommendation | ✅ Prefer this | ⚠️ Legacy |
at() — Modern Index Access (ES2022)
const lang = "JavaScript";
console.log(lang.at(0)); // first character
console.log(lang.at(-1)); // last character (clean!)
console.log(lang.at(-3)); // third from endJ t i
at(-1)is much cleaner thanstr[str.length - 1]for the last character.
split() — String to Array
// Split by a delimiter
const sentence = "JavaScript is awesome and fun";
const words = sentence.split(" ");
console.log(words);
console.log(words.length);
// Split each character
const chars = "Hello".split("");
console.log(chars);
// Split with limit
const limited = "a,b,c,d,e".split(",", 3);
console.log(limited);[ 'JavaScript', 'is', 'awesome', 'and', 'fun' ] 5 [ 'H', 'e', 'l', 'l', 'o' ] [ 'a', 'b', 'c' ]
Reverse a string using split
const word = "JavaScript";
const reversed = word.split("").reverse().join("");
console.log(reversed);tpircSavaJ
padStart() and padEnd()
Used to pad a string to a minimum length — great for formatting.
000042 Ali............done Priya..........done Christopher....done
repeat()
------------------------------ ⭐⭐⭐⭐⭐ [███░░░░░░░] 30% [███████░░░] 70% [██████████] 100%
toString() and String()
42 101010 2a true null undefined
Method Chaining
Multiple methods can be chained — each returns a new string:
const raw = " HELLO, JAVASCRIPT WORLD! ";
const processed = raw
.trim()
.toLowerCase()
.replace("javascript", "JS");
console.log(processed);hello, js world!
Chain execution:
" HELLO, JAVASCRIPT WORLD! "
↓ .trim()
"HELLO, JAVASCRIPT WORLD!"
↓ .toLowerCase()
"hello, javascript world!"
↓ .replace()
"hello, js world!"All String Methods — Quick Reference Table
| Method | What it does | Returns |
|---|---|---|
toUpperCase() | Convert to uppercase | String |
toLowerCase() | Convert to lowercase | String |
trim() | Remove leading/trailing whitespace | String |
trimStart() | Remove leading whitespace | String |
trimEnd() | Remove trailing whitespace | String |
slice(s, e) | Extract substring (supports negative) | String |
substring(s, e) | Extract substring (no negative) | String |
at(n) | Get char at index (supports negative) | String |
charAt(n) | Get char at index | String |
split(delim) | Split into array | Array |
padStart(n, ch) | Pad start to length n | String |
padEnd(n, ch) | Pad end to length n | String |
repeat(n) | Repeat string n times | String |
toString() | Convert to string | String |
concat(...strs) | Join strings | String |
includes(str) | Check if contains | Boolean |
startsWith(str) | Check if starts with | Boolean |
endsWith(str) | Check if ends with | Boolean |
indexOf(str) | Find first position | Number |
lastIndexOf(str) | Find last position | Number |
replace(old, new) | Replace first match | String |
replaceAll(old, new) | Replace all matches | String |
Common Mistakes ❌
1. Forgetting strings are immutable
// ❌ Wrong — ignoring the return value
let name = " riya sharma ";
name.trim(); // result is discarded!
console.log(name); // " riya sharma " (unchanged)
// ✅ Correct — capture the result
name = name.trim();
console.log(name); // "riya sharma"2. slice vs substring with negative indices
const s = "JavaScript";
// ❌ Using substring expecting negative to work like slice
console.log(s.substring(-4)); // "JavaScript" — not "ipt"!
// ✅ Use slice for negative indices
console.log(s.slice(-4)); // "ipt" (last 4)3. split("") vs split() behavior difference
Interview Questions 🎯
Q1. What does trim() do and what are its variants? > trim() removes whitespace from both ends. trimStart() removes from the left only; trimEnd() from the right only.
Q2. What is the difference between slice() and substring()? > Both extract a substring. slice() supports negative indices (count from end). substring() treats negative indices as 0 and swaps arguments if start > end. Prefer slice().
Q3. How do you reverse a string in JavaScript? > str.split("").reverse().join("") — split into characters, reverse the array, join back.
Q4. What does padStart() do and give a real use case? > It pads the beginning of a string with a fill character until it reaches a target length. Use case: formatting invoice numbers as 000042 from just 42.
Q5. Do string methods mutate the original string? > Never. All string methods return new values. Strings are immutable — you must capture the return value.
Q6. What is the at() method and why is it useful? > at(index) returns the character at the given index, supporting negative indices. str.at(-1) cleanly gets the last character without str[str.length - 1].
Q7. What does split("") return for an empty string? > An empty array []. "".split("") returns [], not [""].
Key Takeaways 🏁
- All string methods return new strings — the original is always preserved
trim()is essential for cleaning user inputslice(start, end)is the go-to for extraction — supports negative indicesat(-1)is the modern, clean way to get the last charactersplit(delim)converts string to array;join(delim)does the reversepadStart/padEndare great for consistent-width number formatting- Method chaining makes complex transformations readable
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript String Methods - Complete Reference with Examples & Output.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, strings, string, methods
Related JavaScript Master Course Topics