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.

6 min read

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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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

MethodWhat it doesReturns
includes(sub)Checks if substring existsBoolean
startsWith(sub)Checks prefixBoolean
endsWith(sub)Checks suffixBoolean
indexOf(sub)Position of first matchNumber or -1
slice(start, end)Extracts a sectionNew string
split(sep)Splits into arrayArray
replace(old, new)Replaces first matchNew string
replaceAll(old, new)Replaces all matchesNew string
toLowerCase()Converts to lowercaseNew string
toUpperCase()Converts to uppercaseNew string
trim()Removes surrounding whitespaceNew string
repeat(n)Repeats string n timesNew string
padStart(len, ch)Pads beginningNew string
padEnd(len, ch)Pads endNew string
at(pos)Character at positionSingle 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

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.
RunePowered by Rune AI

Frequently Asked Questions

Do string methods modify the original string?

No. Strings in JavaScript are immutable. Every string method returns a new string and leaves the original unchanged. You must assign the result to a variable if you want to keep it.

How many string methods does JavaScript have?

JavaScript has around 30 built-in string methods on the String prototype, plus static methods like String.fromCharCode(). This guide covers the most practical ones for everyday development.

Can I chain string methods together?

Yes. Because each method returns a string, you can call another method on the result. For example: str.trim().toLowerCase().replace('a', 'b').

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.