iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

MethodWhat it doesExample
lengthCharacter count."hello".length → 5
toUpperCase / toLowerCaseCase conversion."Hi".toUpperCase() → "HI"
trim / trimStart / trimEndStrip 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 / endsWithEdge tests."file.pdf".endsWith(".pdf")
padStart / padEndPad 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. ();

Test yourself

Q1. Strings in JS are…
Q2. Replace EVERY match of "-" with "_" using…
Q3. Check if a string starts with "/api/" with…

Discussion

Loading…