Lesson ยท 9 min
Text and strings
Strings are values with tools
You met strings in the first lesson. A string is a piece of text. Every string has properties and methods that you reach with a dot.
const city = 'Lisbon';
console.log(city.length); // 6
console.log(city.toUpperCase()); // LISBON
- A property is a fact about the value, such as
length. It has no parentheses. - A method is an action that the value can do, such as
toUpperCase(). It has parentheses, and sometimes it has values inside them.
A method does not change the string. It gives you a new string, and you can keep it in a variable.
Useful methods
| Code | Result |
|---|---|
'hello'.toUpperCase() |
'HELLO' |
'HELLO'.toLowerCase() |
'hello' |
' hi '.trim() |
'hi' |
'hello'.slice(1, 3) |
'el' |
'hello'.indexOf('l') |
2 |
'hello'.includes('ell') |
true |
'a-b-c'.split('-') |
['a', 'b', 'c'] |
'ha'.repeat(3) |
'hahaha' |
Positions start at zero
The first character of a string is at position 0, not 1. In 'hello', the letter h is at position 0, and o is at position 4.
Joining strings
Use + to join strings: 'Hello, ' + name. A template string does the same and is easier to read: `Hello, ${name}`.
Your turn
The constant name is already in the editor. Write your code under it.
Tasks
5 to do
Task 1, not checked yet. Make a constant
shoutthat holdsnamein capital letters. Use the string methodtoUpperCase().Task 2, not checked yet. Make a constant
sizethat holds the number of characters inname. Use thelengthproperty.Task 3, not checked yet. Make a constant
firstthat holds the first three characters ofname. Use theslicemethod.Task 4, not checked yet. Make a constant
hasLovethat istruewhennameincludes the textLove. Use theincludesmethod.Task 5, not checked yet. Print the sentence
Hello, Ada! Your name has 12 letters and spaces.Build it with a template string that usesfirstandsize.
Task 1 of 5
Make a constant shout that holds name in capital letters. Use the string method toUpperCase().