String Superpowers

Grade 2, page 4 of 13. A three-minute read.

Strings come with a whole toolbox of built-in abilities. Let's look at the most useful ones.

How long is it?

Every string knows its own length. Just add .length:

JavaScript
const word = "JavaScript";
console.log(word.length);
console.log("".length);
console.log("Hi there!".length);

It prints

10
0
9

Spaces and punctuation count as characters too, so "Hi there!" has 9 characters.

Grabbing a single character

Each character in a string has a position number, called its index. You can grab a character with square brackets:

JavaScript
const word = "PIZZA";
console.log(word[0]);
console.log(word[1]);
console.log(word[4]);

It prints

P
I
A

Wait, why is word[0] the first letter? Shouldn't the first letter be number 1?

Welcome to one of programming's most famous quirks: counting starts at zero. The first character is at index 0, the second is at index 1, and so on. So in "PIZZA":

CharacterPIZZA
Index01234

The string has a length of 5, but the last index is 4. This trips up everybody at first. Don't worry, you'll get lots of practice in Grade 7 (where we finally explain the Grade 13 joke).

To get the last character, you can use word[word.length - 1], or the shorter modern way, .at(-1):

JavaScript
const word = "PIZZA";
console.log(word[word.length - 1]);
console.log(word.at(-1));
console.log(word.at(-2));

It prints

A
A
Z

With .at(), negative numbers count backwards from the end. -1 is the last character, -2 is the second-to-last, and so on.

String methods

A method is an action that a value can perform. You call a method by writing a dot, the method's name, and parentheses, just like console.log(). Here are the string methods you'll use most:

JavaScript
const shout = "hello";
const whisper = "QUIET PLEASE";
const messy = "    too much space    ";

console.log(shout.toUpperCase());
console.log(whisper.toLowerCase());
console.log(messy.trim());

It prints

HELLO
quiet please
too much space
  • toUpperCase() makes every letter a capital.
  • toLowerCase() makes every letter small.
  • trim() chops off spaces from the beginning and end (super handy for cleaning up what users type).

Searching inside strings

JavaScript
const sentence = "I love fried rice";

console.log(sentence.includes("fried"));
console.log(sentence.includes("pizza"));
console.log(sentence.startsWith("I"));
console.log(sentence.endsWith("rice"));
console.log(sentence.indexOf("love"));
console.log(sentence.indexOf("pizza"));

It prints

true
false
true
true
2
-1
  • includes(text) answers "is this text somewhere inside?" with true or false.
  • startsWith(text) and endsWith(text) check the beginning and end.
  • indexOf(text) tells you where the text starts (its index). If it's not found at all, you get -1, which is JavaScript's way of saying "nope, not here."

Cutting and changing strings

JavaScript
const fruit = "pineapple";

console.log(fruit.slice(0, 4));
console.log(fruit.slice(4));
console.log(fruit.replace("apple", "cone"));
console.log("ha".repeat(3));
console.log("7".padStart(3, "0"));

It prints

pine
apple
pinecone
hahaha
007
  • slice(start, end) cuts out part of a string, from the start index up to, but not including, the end index. Leave out end and it goes all the way to the end of the string.
  • replace(old, new) swaps the first match of old for new. (There's also replaceAll to swap every match.)
  • repeat(n) repeats the string n times.
  • padStart(length, filler) adds filler characters to the start until the string is a certain length. Bond. James Bond.

You can chain methods together

Since each method gives you back a new string, you can immediately call another method on it:

JavaScript
const input = "   OmAr   ";
const cleaned = input.trim().toLowerCase();
console.log(`[${cleaned}]`);

It prints

[omar]

JavaScript does it left to right: first trim(), then toLowerCase() on the result.

Watch outStrings can't be changed in place

String methods never change the original string. They always make a new string and give that back to you. Watch:

JavaScript
let name = "mia";
name.toUpperCase();
console.log(name);

It prints

mia

The uppercase version was created... and then thrown straight in the bin because we didn't store it anywhere. To keep it, you have to save the result: name = name.toUpperCase();. Programmers say strings are immutable, which is a fancy word for "unchangeable."

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning