Course outline · 0% complete

0/29 lessons0%

Course overview →

String methods you will actually use

lesson 8-1 · ~10 min · 25/29

Quiz

Warm-up from lesson 7-1: which method keeps only the items that pass a test, possibly returning a shorter array?

The everyday string toolkit

A surprising share of real engineering is text handling: cleaning form input, splitting CSV lines, matching search terms, building URLs and file paths. These are the methods that do that work, and you will type them daily.

Most string methods match Python, renamed in camelCase — JavaScript's convention of gluing words together with capital letters, as in toUpperCase:

JobPythonJavaScript
uppercase / lowercases.upper() / s.lower()s.toUpperCase() / s.toLowerCase()
strip surrounding spacess.strip()s.trim()
contains"x" in ss.includes("x")
starts / endss.startswith / s.endswiths.startsWith / s.endsWith
slice a pieces[0:3]s.slice(0, 3)
split into arrays.split(",")s.split(",")
join array into string",".join(xs)xs.join(",")
replaces.replace(a, b)s.replaceAll(a, b)

Two notes. JavaScript has no s[0:3] slicing syntax, only the slice method. And join flips: Python calls it on the separator, JavaScript calls it on the array.

Strings are immutable, exactly like Python: every method returns a new string and the original is untouched.

Code exercise · javascript

Run it. trim cleans the ends, the query methods answer booleans, and split/join convert between strings and arrays.

Code exercise · javascript

Your turn. Clean up the email address: remove the surrounding spaces and lowercase it, then print it. On the second line print whether the cleaned address ends with .com

Code exercise · javascript

Second practice. Turn the full name into initials: split on spaces, map each word to its first letter uppercased, and join the letters with periods. Print G.B.H

Quiz

const s = "hi"; s.toUpperCase(); console.log(s); What prints?