JS String Methods
Strings are immutable — methods return new strings rather than modifying in place. Here are the ones you'll reach for weekly.
The weekly methods
| Method | What it does | Example |
|---|---|---|
length | Character count. | "hello".length → 5 |
toUpperCase / toLowerCase | Case conversion. | "Hi".toUpperCase() → "HI" |
trim / trimStart / trimEnd | Strip whitespace. | " x ".trim() → "x" |
slice(start, end) | Sub-string (supports negatives). | "hello".slice(1, -1) → "ell" |
split(sep) | Split into an array. | "a,b,c".split(",") → ["a","b","c"] |
replace(pat, repl) | First match replaced. | "a-b".replace("-", "_") |
replaceAll(pat, repl) | Every match replaced. | "a-b-c".replaceAll("-", "_") |
includes(sub) | Does it contain sub? | "hello".includes("ll") → true |
startsWith / endsWith | Edge tests. | "file.pdf".endsWith(".pdf") |
padStart / padEnd | Pad to length. | "5".padStart(2, "0") → "05" |
repeat(n) | Repeat n times. | "ab".repeat(3) → "ababab" |
Common one-liners
JS
// Get the file extension
const ext = name.slice(name.lastIndexOf(".") + 1);
// Title case
const title = s.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
// Reverse
const rev = [...s].reverse().join("");
// Count occurrences
const count = (s.match(/foo/g) || []).length;
Note:
length counts UTF-16 code units. Emoji and rare characters can be more than one — for accurate iteration use [...str] or Array.from(str).Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS String Methods!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Remove leading and trailing whitespace.
const clean = raw.
();
Four letters.
Discussion
Loading…