JavaScript string methods transform, trim, slice, and split text while always returning a brand-new string. Because strings are immutable, none of these methods change the original string variable.
| Method | What It Does | Example Output |
|---|---|---|
trim() |
Removes leading and trailing whitespace | " hi ".trim() -> "hi" |
slice(start, end) |
Extracts a section (supports negative indexes) | "JavaScript".slice(0, 4) -> "Java" |
toLowerCase() |
Converts all letters to lowercase | "JS".toLowerCase() -> "js" |
replaceAll(a, b) |
Replaces every match of a with b |
"a-b-c".replaceAll("-", "_") -> "a_b_c" |
split(sep) |
Splits a string into an array of substrings | "a,b".split(",") -> ["a", "b"] |
padStart(len, ch) |
Pads the start to reach target length | "7".padStart(3, "0") -> "007" |
Real applications frequently clean form inputs and convert raw CSV lines into structured arrays.
const rawEmail = " [email protected] ";
const cleanEmail = rawEmail.trim().toLowerCase();
const tagsCsv = "javascript, es6, dom, async";
const tagList = tagsCsv.split(",").map((tag) => tag.trim());
const slug = "Learn JavaScript Basics".toLowerCase().replaceAll(" ", "-");
console.log({ cleanEmail, tagList, slug });
slice() Beats substr() and substring()Avoid legacy substr(), which is deprecated in modern specifications and behaves inconsistently across edge cases. Prefer slice(start, end) over substring(), because slice() accepts negative offsets like str.slice(-4) to grab characters from the end without swapping arguments silently.
You can also chain string methods cleanly from left to right. Each call returns a fresh string, so the next method in the chain works immediately on the updated output.
str.trim() to mutate str: Writing email.trim(); without assigning the returned string discards the trimmed result.replace() for all occurrences: text.replace("-", "_") replaces only the first match when given a string. Use replaceAll() (ES2021) to replace every match."".split(",") returns [""] (an array with one empty string), not [].Combine indexing or slice(): word ? word[0].toUpperCase() + word.slice(1) : "". Checking for an empty string prevents "undefined" or errors.
trimStart() and trimEnd()?trimStart() removes whitespace only from the beginning of a string, while trimEnd() removes whitespace only from the end.
Call str.repeat(count), such as "-".repeat(10), instead of writing a for loop.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.