Step 1 of 7 · Reading · ~3 min
Learn
Strings
String Basics
A string is a piece of text. By the end of this lesson you can measure a string, pick characters out of it, cut pieces from it, and build a modified copy, without ever expecting the original to change.
Quotes, length and indexing
Single quotes, double quotes and backticks all make strings (backticks get their own lesson). Pick one style and stay with it.
An out-of-range index gives undefined silently, so a wrong index shows up later as a confusing result rather than a crash.
Special characters are written with a backslash: \n is a newline, \t a tab, \" a quote inside double quotes, \\ a backslash.
Strings never change
Every string method returns a new string. To "change" text, build a new string and store or print that.
Cutting pieces with slice
slice(start, end) returns the characters from start up to, but not including, end. Leave end off to go to the finish. A negative number counts from the end.
Slicing past the end is safe: "hi".slice(1) is "i" and "a".slice(1) is "" rather than an error.
Everyday methods
split returns a list of pieces (an array, covered in the arrays lesson), and join glues such a list back into one string. replace(find, with) changes only the FIRST match. To replace every match, split on the old text and join with the new: "a-b-c".split("-").join("+") is "a+b+c".
Joining strings
+ concatenates, and a number next to a string is converted: "item" + 3 is "item3". Pieces can be glued from calls, too: word.slice(0, 1) + "!".
Common mistakes
- Assigning to a character (
s[0] = "X") and expecting the string to change. It never does. - Forgetting that
sliceandtoUpperCasereturn a result. A line such asword.toUpperCase();on its own computes a value and throws it away. - Treating the result of
s.indexOf("x")as a yes/no "contains" answer: a match at index 0 gives0, which counts as false, and no match gives-1, which counts as true. Useincludes, or compare with-1. - Off-by-one with
slice: the end index is excluded, soslice(0, 4)has 4 characters, not 5.
Your exercise
Capitalise a line of text and report its length. The starter reads the line into text. Because strings are immutable, you will build a new string from two parts.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…