JavaScript

Lesson 4 of 11

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

  1. Task 1, not checked yet. Make a constant shout that holds name in capital letters. Use the string method toUpperCase().

  2. Task 2, not checked yet. Make a constant size that holds the number of characters in name. Use the length property.

  3. Task 3, not checked yet. Make a constant first that holds the first three characters of name. Use the slice method.

  4. Task 4, not checked yet. Make a constant hasLove that is true when name includes the text Love. Use the includes method.

  5. Task 5, not checked yet. Print the sentence Hello, Ada! Your name has 12 letters and spaces. Build it with a template string that uses first and size.

Task 1 of 5

Make a constant shout that holds name in capital letters. Use the string method toUpperCase().

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.