String Methods
Learn the most important built-in string methods in JavaScript for searching, transforming, and working with text.
String Methods
JavaScript strings come with a rich set of built-in methods. Every string you create has instant access to these methods — no imports, no setup.
Since strings are immutable, every method here returns a new string. The original is never changed.
Changing Case
toUpperCase() and toLowerCase()
const name = "Ali Hassan";
console.log(name.toUpperCase()); // ALI HASSAN
console.log(name.toLowerCase()); // ali hassan
console.log(name); // Ali Hassan — unchangedReal use — case-insensitive comparison:
const userInput = "JAVASCRIPT";
const tag = "javascript";
console.log(userInput.toLowerCase() === tag); // trueTrimming Whitespace
trim(), trimStart(), trimEnd()
Removes whitespace from both ends, the start only, or the end only.
const raw = " Hello, World! ";
console.log(raw.trim()); // "Hello, World!"
console.log(raw.trimStart()); // "Hello, World! "
console.log(raw.trimEnd()); // " Hello, World!"This is essential when handling user input — people often accidentally add spaces when typing.
const email = " ali@example.com ";
const clean = email.trim().toLowerCase();
console.log(clean); // ali@example.comSearching
includes() — does it contain this?
Returns true or false.
const sentence = "JavaScript is the language of the web";
console.log(sentence.includes("JavaScript")); // true
console.log(sentence.includes("Python")); // false
console.log(sentence.includes("language")); // trueCase sensitive — "javascript" would return false here. Convert to lowercase first for case-insensitive search.
startsWith() and endsWith()
const url = "https://ali.dev/blog";
console.log(url.startsWith("https")); // true
console.log(url.startsWith("http://"));// false
console.log(url.endsWith(".dev/blog")); // true
console.log(url.endsWith(".com")); // falseReal use — checking file extensions or URL protocols:
function isImage(filename) {
const lower = filename.toLowerCase();
return lower.endsWith(".jpg") || lower.endsWith(".png") || lower.endsWith(".webp");
}
console.log(isImage("photo.JPG")); // true
console.log(isImage("document.pdf")); // falseindexOf() and lastIndexOf()
Returns the index of the first or last match. Returns -1 if not found.
const text = "the cat sat on the mat";
console.log(text.indexOf("the")); // 0 — first occurrence
console.log(text.lastIndexOf("the")); // 15 — last occurrence
console.log(text.indexOf("dog")); // -1 — not foundExtracting Parts
slice(start, end)
Returns a portion of the string from start up to but not including end. Does not modify the original.
const text = "JavaScript";
// 0123456789
console.log(text.slice(0, 4)); // Java
console.log(text.slice(4)); // Script — to the end
console.log(text.slice(-6)); // Script — last 6 characters
console.log(text.slice(0, -6)); // Java — everything except last 6Real use — extracting parts of a string:
const email = "ali@example.com";
const username = email.slice(0, email.indexOf("@"));
const domain = email.slice(email.indexOf("@") + 1);
console.log(username); // ali
console.log(domain); // example.comsubstring(start, end)
Similar to slice() but does not support negative indexes. Use slice() in modern code — it is more flexible.
const text = "JavaScript";
console.log(text.substring(0, 4)); // Java
console.log(text.substring(4)); // ScriptReplacing
replace() — replace first match
const sentence = "I love cats. Cats are great.";
console.log(sentence.replace("cats", "dogs"));
// "I love dogs. Cats are great." — only first match, case sensitivereplaceAll() — replace all matches
console.log(sentence.replaceAll("cats", "dogs"));
// "I love dogs. Cats are great." — still case sensitiveFor case-insensitive replacement, use a regular expression with the i flag:
console.log(sentence.replace(/cats/gi, "dogs"));
// "I love dogs. dogs are great." — all occurrences, any caseRegular expressions are a powerful pattern-matching tool. We touch on them here where relevant — a full deep dive would be its own topic.
Real use — cleaning up user input:
const username = " Ali Hassan ";
const slug = username.trim().toLowerCase().replaceAll(" ", "-");
console.log(slug); // ali-hassanSplitting and Joining
split() — string to array
Splits a string into an array at every occurrence of the separator.
const sentence = "JavaScript is awesome";
const words = sentence.split(" ");
console.log(words); // ["JavaScript", "is", "awesome"]
const csv = "Ali,Sara,Zara,Omar";
const names = csv.split(",");
console.log(names); // ["Ali", "Sara", "Zara", "Omar"]Split into individual characters by passing an empty string:
const word = "hello";
console.log(word.split("")); // ["h", "e", "l", "l", "o"]Limit the number of splits with a second argument:
const text = "one two three four";
console.log(text.split(" ", 2)); // ["one", "two"]join() — array to string
The reverse of split() — lives on arrays, not strings. Joins array items into a string.
const words = ["JavaScript", "is", "awesome"];
console.log(words.join(" ")); // "JavaScript is awesome"
console.log(words.join("-")); // "JavaScript-is-awesome"
console.log(words.join("")); // "JavaScriptisawesome"split() and join() work great together for transforming strings:
// Capitalize first letter of every word
const title = "the quick brown fox";
const capitalized = title
.split(" ")
.map(word => word[0].toUpperCase() + word.slice(1))
.join(" ");
console.log(capitalized); // The Quick Brown FoxPadding
padStart() and padEnd()
Pads a string with another string until it reaches the target length.
const num = "5";
console.log(num.padStart(3, "0")); // "005" — pad at start
console.log(num.padEnd(3, "0")); // "500" — pad at endReal use — formatting numbers consistently:
const hours = "9";
const minutes = "5";
console.log(`${hours.padStart(2, "0")}:${minutes.padStart(2, "0")}`);
// "09:05"Repeating
repeat()
Returns the string repeated a given number of times.
console.log("ha".repeat(3)); // hahaha
console.log("* ".repeat(5)); // * * * * *
console.log("-".repeat(20)); // --------------------charAt() and charCodeAt()
charAt() returns the character at a given index — same as bracket notation.
const name = "Ali";
console.log(name.charAt(0)); // A
console.log(name[0]); // A — same resultcharCodeAt() returns the Unicode value of the character at that index.
console.log("A".charCodeAt(0)); // 65
console.log("a".charCodeAt(0)); // 97
console.log("0".charCodeAt(0)); // 48The reverse — String.fromCharCode() — converts a Unicode value back to a character:
console.log(String.fromCharCode(65)); // A
console.log(String.fromCharCode(97)); // aMethod Chaining
Since every method returns a new string, you can chain them:
const raw = " HELLO, WORLD! ";
const clean = raw
.trim()
.toLowerCase()
.replace("world", "DocsHub");
console.log(clean); // "hello, docsHub!"Quick Reference
| Method | What it does |
|---|---|
toUpperCase() | All uppercase |
toLowerCase() | All lowercase |
trim() | Remove whitespace from both ends |
includes(str) | Check if string contains str |
startsWith(str) | Check if starts with str |
endsWith(str) | Check if ends with str |
indexOf(str) | Index of first match, -1 if not found |
slice(start, end) | Extract portion of string |
replace(a, b) | Replace first match |
replaceAll(a, b) | Replace all matches |
split(sep) | Split into array |
padStart(n, str) | Pad beginning to reach length n |
padEnd(n, str) | Pad end to reach length n |
repeat(n) | Repeat string n times |
charAt(i) | Character at index i |
A Real Example — Username Validator
function validateUsername(input) {
const username = input.trim();
if (username.length < 3) {
return "Username must be at least 3 characters.";
}
if (username.length > 20) {
return "Username must be 20 characters or less.";
}
if (username.includes(" ")) {
return "Username cannot contain spaces.";
}
if (!username[0].match(/[a-zA-Z]/)) {
return "Username must start with a letter.";
}
return `Username "${username.toLowerCase()}" is valid!`;
}
console.log(validateUsername(" Ali ")); // Username "ali" is valid!
console.log(validateUsername("a")); // Username must be at least 3 characters.
console.log(validateUsername("ali hassan")); // Username cannot contain spaces.
console.log(validateUsername("123ali")); // Username must start with a letter.
console.log(validateUsername("ali_dev_2024")); // Username "ali_dev_2024" is valid!Summary
- All string methods return new strings — originals are never changed
- Case —
toUpperCase(),toLowerCase() - Trimming —
trim(),trimStart(),trimEnd() - Searching —
includes(),startsWith(),endsWith(),indexOf() - Extracting —
slice()— supports negative indexes, preferred oversubstring() - Replacing —
replace()first match,replaceAll()all matches - Splitting —
split()string into array, pair withjoin()to rebuild - Padding —
padStart(),padEnd()— great for formatting numbers - Repeating —
repeat() - Chain methods together for clean multi-step transformations