Strings
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Strings are text
- A string is text inside quotes:
"Ada"or'Ada'. - Join strings with
+— this is called concatenation.
let first = "Ada";
console.log("Hi, " + first + "!"); // → Hi, Ada!
Length and capitals
.lengthcounts the characters..toUpperCase()and.toLowerCase()return a copy in CAPITALS or small letters.
console.log("hello".length); // → 5
console.log("hello".toUpperCase()); // → HELLO
Reach inside a string
- Each character has a position, counting from 0:
text[0]is the first one. .slice(start, end)takes the part fromstartup to — but not including —end.
let word = "JAVASCRIPT";
console.log(word[0]); // → J
console.log(word.slice(0, 4)); // → JAVA
Explore
Index and slice a string
Characters are numbered from 0. A slice takes from start up to — but not including — end.
Watch out
- Positions start at
0, so the 4th character isword[3]. - String methods return a new string — the original never changes.
Common mistakes
- Index from
0;s.lengthis a property (no()). - Strings cannot be changed in place.
Now you try
- Build and inspect strings.
- Press Check answer to test it.
let name = "Sam". Use + to log Hello, then the name then !, so it reads Hello, Sam!.
Click Run to see the output here.
Log how many characters are in the string computer using .length (it is 8).
Click Run to see the output here.
Log the string cat in CAPITALS using .toUpperCase() (it is CAT).
Click Run to see the output here.
let word = "code". Log just its first letter using word[0] (it is c).
Click Run to see the output here.