JavaScript String Methods: Complete Guide
A categorized overview of JavaScript string methods with practical examples. Learn which methods to use for searching, extracting, transforming, and formatting strings.
JavaScript string methods are built-in functions that let you search, extract, change, and format text. Every string value automatically has access to these methods without importing a library or installing anything.
Here is a quick taste of the most common ones at work:
const text = " Learn JavaScript ";
console.log(text.trim());
console.log(text.trim().toLowerCase());
console.log(text.trim().includes("Java"));
console.log(text.trim().slice(0, 5));The first call prints Learn JavaScript with surrounding spaces removed. The second prints learn javascript by chaining trim and toLowerCase.
The third prints true because "Java" exists inside the trimmed string. The fourth prints Learn by extracting the first five characters.
Each method returns a new string. The original text variable never changes.
This is the first rule: strings are immutable. Every method gives you a new string instead of modifying the original.
The methods by category
The most practical string methods group into four categories based on what you want to accomplish.
Search and check methods
These methods answer questions about what a string contains and where.
The methods includes, startsWith, and endsWith all return a boolean:
const url = "https://rune.codes/javascript";
console.log(url.includes("rune"));
console.log(url.startsWith("https"));
console.log(url.endsWith("javascript"));All three print true. They are case-sensitive, so url.includes("Rune") would return false. For a deep dive into these three, see the guide to includes, startsWith, and endsWith.
The methods indexOf and lastIndexOf return the position of a match, or -1 when nothing is found:
const phrase = "JavaScript is fun. JavaScript is powerful.";
console.log(phrase.indexOf("JavaScript"));
console.log(phrase.lastIndexOf("JavaScript"));
console.log(phrase.indexOf("Python"));The first call prints 0 because "JavaScript" starts at position zero. The second prints 20, the last occurrence position. The third prints -1 because "Python" does not appear.
Extraction methods
These methods pull out parts of a string.
The slice method extracts a section using start and end positions. Negative indices count from the end:
const word = "JavaScript";
console.log(word.slice(0, 4));
console.log(word.slice(-3));The first call prints Java by going from position 0 up to but not including 4. The second prints ipt because -3 means "three characters from the end." See the guide to slice, substring, and substr for a full comparison.
The split method breaks a string into an array at a separator. It is one of the most commonly used string operations:
const csv = "apple,banana,grape,orange";
const fruits = csv.split(",");
console.log(fruits);
console.log(fruits[1]);The first log shows ["apple", "banana", "grape", "orange"]. The second prints banana, the item at index 1.
The charAt method gets a single character. The newer at method supports negative indices:
const word = "Hello";
console.log(word.charAt(1));
console.log(word.at(-1));The first prints e. The second prints o, the last character.
With charAt, getting the last character requires word.charAt(word.length - 1), which is longer and easier to get wrong.
Transformation methods
toLowerCase and toUpperCase change casing. They are commonly chained with trim to normalize user input:
const userAnswer = " YES ";
if (userAnswer.trim().toLowerCase() === "yes") {
console.log("Confirmed!");
}This prints Confirmed! regardless of how the user typed the input.
Uppercase, lowercase, mixed case, and extra surrounding spaces all normalize to the same comparison value after chaining trim and toLowerCase together.
trim, trimStart, and trimEnd remove whitespace from the ends of a string:
const raw = " hello world ";
console.log(`|${raw.trim()}|`);
console.log(`|${raw.trimStart()}|`);The first prints |hello world| because trim removes whitespace from both ends.
The second prints |hello world | because trimStart only removes leading spaces, leaving the trailing ones intact. These methods are essential for cleaning form input before processing.
replace and replaceAll swap text within a string:
const sentence = "cats are great. cats are fluffy.";
console.log(sentence.replace("cats", "dogs"));
console.log(sentence.replaceAll("cats", "dogs"));The first prints dogs are great. cats are fluffy. because replace only swaps the first match.
The second prints dogs are great. dogs are fluffy. because replaceAll swaps every occurrence, no regex needed.
Format and pad methods
repeat duplicates a string. padStart and padEnd add characters to reach a target length:
console.log("ha".repeat(3));
console.log("42".padStart(5, "0"));
console.log("42".padEnd(5, "."));The first prints hahaha. The second prints 00042 by padding with zeros until five characters.
The third prints 42... by padding with dots. Zero-padding is common for formatting invoice IDs or clock displays.
Quick reference table
| Method | What it does | Returns |
|---|---|---|
| includes(sub) | Checks if substring exists | Boolean |
| startsWith(sub) | Checks prefix | Boolean |
| endsWith(sub) | Checks suffix | Boolean |
| indexOf(sub) | Position of first match | Number or -1 |
| slice(start, end) | Extracts a section | New string |
| split(sep) | Splits into array | Array |
| replace(old, new) | Replaces first match | New string |
| replaceAll(old, new) | Replaces all matches | New string |
| toLowerCase() | Converts to lowercase | New string |
| toUpperCase() | Converts to uppercase | New string |
| trim() | Removes surrounding whitespace | New string |
| repeat(n) | Repeats string n times | New string |
| padStart(len, ch) | Pads beginning | New string |
| padEnd(len, ch) | Pads end | New string |
| at(pos) | Character at position | Single char |
Common mistakes
The most frequent error is expecting the original string to change. Calling name.toUpperCase() without capturing the result leaves name unchanged. You must assign: name = name.toUpperCase().
Treating indexOf as a boolean is another trap. The expression str.indexOf("H") returns 0 when "H" is at the first position, and 0 is falsy in JavaScript.
Always compare explicitly: str.indexOf("H") !== -1. Better yet, use includes() when you only need a yes or no answer.
Using substr instead of slice is a legacy habit. The substr method is deprecated and uses a confusing length-based second argument. Prefer slice(start, end) for all extraction because its negative-index behavior matches array slice.
Rune AI
Key Insights
- String methods do not change the original string. They always return a new one.
- Use includes, startsWith, and endsWith for checking substrings.
- Use slice for extracting parts of a string. Avoid substr, which is deprecated.
- Use replace, toLowerCase, trim, and split for everyday transformations.
- Chain methods together when you need multiple operations on the same string.
Frequently Asked Questions
Do string methods modify the original string?
How many string methods does JavaScript have?
Can I chain string methods together?
Conclusion
JavaScript string methods give you a complete toolkit for searching, extracting, transforming, and formatting text. The most commonly used methods are includes, slice, replace, split, trim, toLowerCase, and startsWith. Learn these seven first, then explore the rest as you need them.
More in this topic
Is JavaScript Frontend or Backend? Full Guide
JavaScript is both a frontend and backend language. Learn the difference between browser JavaScript and Node.js, what each is used for, and which one you should learn first.
Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
JavaScript Tutorial: Complete Beginner's Guide to Programming in 2025
A structured learning path for absolute beginners. Learn what to study first, how to practice, and which JavaScript concepts matter most when you are starting from zero.