Call a string’s methods and read its length. Tidy text with trim, toUpperCase and toLowerCase, and keep the new string each one gives back, because the old one never changes. Chain methods, ask questions with includes, startsWith and endsWith, count positions from 0 with indexOf and slice, read TS2551, and make TaskKit tidy its task names.
TypeScript
Fundamentals
Working with strings: common methods. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
On the fridge in a shared flat hangs a shopping list. Ana wrote
Buy milk on it on Monday. On Tuesday someone who had not read
the list added buy MILK, with stray spaces around it, and on
Wednesday a third person wrote buy milk at the bottom. Anyone
who reads the list knows it asks for one carton of milk, not
three.
A program does not know that. In the last lesson you saw that ===
calls two strings equal only when every character matches, capital
letters included. A space is a character too, so to TaskKit those
are three different tasks. Soon TaskKit's task names will come from
whoever types them, and people type extra spaces, or lower case
where a capital belongs. Every string carries a set of tools for
exactly this job. By the end of this lesson you will measure a piece
of text, ask whether it contains a word, cut a piece out of it, and
make a tidy copy of it, and TaskKit will print Buy milk even when
the name was typed as buy milk.
Methods: commands a string carries
You have already used one. In Module 1 TaskKit's banner got its line
from "=".repeat(28): the value, a dot, the name of a command, and
what it needs in the brackets, (), the parentheses of the last
lesson. A command that belongs to a value and is written after it
with a dot is called a method. console.log is built the same
way: log is a method that belongs to console.
Every string comes with a few dozen methods, and MDN (Mozilla's
JavaScript documentation, short for Mozilla Developer Network) has a
page for each of them, under String, laid out like the repeat()
page you read in Module 1. You do not need them all. This lesson
covers about ten that programs use every day.
Some things about a string do not need any work, only an answer.
How long is it? A property is a fact that a value carries
with it. You read it with a dot and its name, and no brackets,
because nothing has to be done. length is the number of
characters in a string, spaces included:
It prints 8, 10 and 0. The space in the middle of
Buy milk is a character like any other, and so are the spaces
at the ends. The empty string has no characters at all.
Every string method gives something back, and so does a property
such as length; what you can do next depends on its type. Three
kinds cover everything in this lesson. In the figure, slice(0, 3)
and indexOf count positions from 0; a later section explains why:
Does: Counts characters, or finds where one starts
Never: length never takes brackets
With task = "Buy milk": each method gives back one type
The brackets are what tell a method from a property. A method
does some work, so it is called with brackets, even when there is
nothing to put in them: task.toUpperCase(). A property is only
read: write task.length() and TypeScript refuses it with
This expression is not callable., because a number is not a
command. The rest of this lesson takes the three kinds one at a
time.
A new string, and the old one untouched
Three methods do most of the tidying. trim() removes the spaces,
and other blank characters such as tabs, at the start and the end of
a string, and never the ones between words. toUpperCase() turns
every letter into a capital, and toLowerCase() makes every letter
lower case; anything that is not a letter stays as it is.
The first line prints Buy Milk, with no spaces round it. The
other two keep the spaces, since only trim() removes them, and
print BUY MILK and buy milk.
Think of a photocopier with a few buttons: enlarge, black and
white, crop the edges. You put a page in, press a button, and get
a changed copy out. The page you put in comes back exactly as it
was. A string method works the same way: it never changes the
string it is called on. It makes a new one and gives it back, and
if you want to keep the copy, you put it in a box of its own.
Press Next step to watch it happen:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
task" buy milk "" buy milk "
tidy"buy milk""buy milk"
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 1.task = " buy milk ".
A box task holds the name as it was typed: a space at each end.
Line 2.task = " buy milk ", tidy = "buy milk".
trim() gives back a new string without the end spaces. It goes
into a new box; task is untouched.
Line 3.task = " buy milk ", tidy = "buy milk".
task still has both spaces, so it is 10 characters long.
Prints 10
Line 4.task = " buy milk ", tidy = "buy milk".
The tidy copy is 8 characters: the same words, no spaces.
Prints 8
trim() gives back a new string, and task keeps its spaces
Because the method gives its answer back rather than changing
anything, a line that calls a method and does nothing with the
answer does nothing at all.
Bad — trim() makes a tidy copy,
and the line throws it away.
The square brackets around the placeholder are only there to
show where the text starts and ends. Run both. The first prints
Added: [ buy milk ], spaces and all, and nothing warns you:
calling a method and ignoring its answer is allowed. When a method
seems to have done nothing, look for the box its answer should
have gone into.
Two more methods make changed copies. replace() takes two
strings: the text to find, and the text to put in its place. It
replaces the first match only. replaceAll() replaces every
match:
It prints Buy bread, then 2026/10-12, where only the first
dash changed, then 2026/10/12, and last Buy milk. After all
that work, task still holds what it was given on line 1.
One dot after another
A method that gives back a string gives back something that has
methods of its own. So you can put another dot straight after the
brackets and call the next one, without a box in between:
task.trim().toUpperCase(). Calling methods one after another
like this is called chaining. The dots are worked out from
left to right, and each method works on what the one before it
gave back. Press Next step to follow it, or let it play:
" buy milk ".trim().toUpperCase()
Two methods on one string. The left dot goes first, so
trim() runs on the text as it was typed.
"buy milk".toUpperCase()
trim() gave back a new string without the end spaces. The
next dot works on that new string.
"BUY MILK"
toUpperCase() gives back the capitals. Each dot made a new
string; the typed text was never changed.
Two dots, left to right: each method works on the string before it
All 3 steps shown.Step 1 of 3: " buy milk ".trim().toUpperCase()Step 2 of 3: "buy milk".toUpperCase()Step 3 of 3: "BUY MILK"
All 3 steps shown.
Chaining is what settles the shopping list. Make a tidy copy of
each version, with no end spaces and in lower case, and then
compare the copies:
It prints Same task: true. Both copies are buy milk, so ===
finds every character equal.
Asking questions about text
Some methods do not make a new string. They answer a question
about the one they are called on, so they give back a boolean,
just like the comparisons of the last lesson.
includes("…") asks whether the text appears anywhere in the
string.
startsWith("…") asks whether the string begins with it.
endsWith("…") asks whether the string ends with it.
questions.tsts
const task = "Call the dentist";console.log(task.includes("dentist"));console.log(task.startsWith("Call"));console.log(task.endsWith("ist"));console.log(task.includes("call"));console.log(task.toLowerCase().includes("call"));
The first three print true. The fourth prints false: the task
says Call, with a capital, and a lower-case c is a different
character. When capitals should not matter, make the string lower
case first and ask with a lower-case word, as the last line does.
It prints true.
In the next module answers like these decide what TaskKit does: it
will refuse a task whose name is empty.
Positions, counted from zero
Every character in a string has a place in it, numbered from the
left. That number is the character's index, and it starts at
0, not 1. In the table, ␣ stands for the space:
Character
B
u
y
␣
m
i
l
k
Index
0
1
2
3
4
5
6
7
It helps to read an index as "how many characters come before
this one". Nothing comes before B, so its index is 0. Four
characters come before m, so its index is 4. And the last index
is always one less than the length: "Buy milk" has 8 characters,
numbered 0 to 7.
indexOf("…") finds where a piece of text starts and gives back
its index. If the text is not there at all, it gives back -1, a
number no character can have. slice() cuts a piece out: give it
the index to start at and the index to stop at, and it gives back
the characters from the first up to, but not including, the
second. Leave out the second number and it goes to the end:
It prints 4, -1, Buy and milk. slice(0, 3) stops before
index 3, the space, so it takes three characters: as long as both
numbers are inside the string and the second is not smaller than the
first, the second minus the first is how many you get.
slice() and toUpperCase() together can give a name a capital
first letter, the way TaskKit will. slice(0, 1) is the first
character alone, and slice(1) is everything after it. Press
Step instead of Run to watch each box fill:
capital.tsts
const task = "call the dentist";const first = task.slice(0, 1).toUpperCase();const rest = task.slice(1);console.log(first + rest);
first holds C, rest holds all the dentist, and + joins
the two strings into Call the dentist.
TaskKit tidies its tasks
In the last lesson of this module TaskKit starts reading task names
from what you type in the terminal, so they will arrive however a
person typed them. Get it ready now: write the two names the untidy
way, and let TaskKit tidy them before it prints anything. Open
index.ts in ~/projects/taskkit and replace the two lines that
make firstTask and secondTask. The lines marked + are new, and
the ones marked - go:
index.tsts
const version = "0.1";const line = "=".repeat(28);console.log(line);console.log("TaskKit", version);console.log("Your tasks, in your terminal");console.log(line);const limit = 5;let added: number = 0;const firstTask = "Buy milk";const tidyFirst = " buy milk ".trim();const firstTask = tidyFirst.slice(0, 1).toUpperCase() + tidyFirst.slice(1);console.log("Added:", firstTask);added = added + 1;const secondTask = "Call the dentist";const tidySecond = "call the dentist ".trim();const secondTask = tidySecond.slice(0, 1).toUpperCase() + tidySecond.slice(1);console.log("Added:", secondTask);added = added + 1;const room = limit - added;console.log( `Tasks added: ${added} of ${limit}, room for ${room} more`);
Each name takes two steps: trim() makes a tidy copy, and the next
line builds the name from that copy's first letter, in capitals, and
the rest. The lines that make firstTask and secondTask are long,
so each breaks after the =; that changes nothing. Check the file
with tsc (short for TypeScript compiler), which npx starts,
then run it:
bash
npx tsc --noEmit index.tsnode index.ts
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call the dentistTasks added: 2 of 5, room for 3 more
The output is the same as at the end of the last lesson, and that
is the point: the names went in untidy and came out tidy. Change
" buy milk " to " buy milk" or to "buy milk", run it
again, and Added: Buy milk does not change.
Predict before you run
Positions are where most slips with strings happen, because it is
easy to start counting at 1. Count before you run this.
Predict
What is the second line this program prints?
ts
const task = "Call the dentist";console.log(task.slice(0, 4).toUpperCase());console.log(task.indexOf("the"));
The common mistake: a wrong capital letter
Method names are made of several words joined together, and
every word after the first starts with a capital letter:
toUpperCase, startsWith, indexOf, replaceAll. Spelling is
only half of a method's name. The capitals are the other half,
and a capital in the wrong place makes it a name that does not
exist.
Common mistake
Writing a method name with the wrong capitals
You tidy a task name and want it in capitals, so you write the
method's name with "uppercase" as one word, the way it is usually
spelled in English. VS Code (Visual Studio Code, your editor) draws a
wavy line under it, and npx tsc --noEmit index.ts refuses line 4
with TS2551, before anything runs:
TypeScript looks the name after the dot up among everything a string
carries, its methods and its properties, and finds no toUppercase;
the message calls any such name a property. It ends with a guess, as
Did you mean did in Module 1, and here the guess is right. When
TypeScript has no guess, as for tidy.toUpper(), the same message
comes without Did you mean, under the code TS2339. Call it
straight on a const box filled from quotes, as in const task = "Buy milk";, and the message names the type as '"Buy milk"', the
text itself, instead of 'string'. Read it as 'string'; the
lesson on inference, later in this module, explains why.
Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
The fix
Write the name as the string has it, with a capital C:
Run the broken file with node alone and nothing checks it: line
3 prints Added: buy milk, and then line 4 stops the program
with TypeError: tidy.toUppercase is not a function. Either way,
when a message says a name does not exist on type 'string',
compare the name after the dot with the guess, or with the title
of its page on MDN, letter by letter, capitals included.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. The first two ask you
to read code, the last two to change and write it.
Exercise · Read the code
Keep the tidy copy
task holds " buy milk ". Which line leaves the tidy name,
"buy milk", in a box called tidy?
Exercise · Predict the result
Cut a piece out
What does this line print? Write the text without quotes.
ts
console.log("Buy milk".slice(4, 6));
Exercise · Fix the error
Tidy it, then shout it
This program should print Added: BUY MILK, with no spaces
around the name. TypeScript refuses it, and once that is fixed it
still prints the spaces. Fix both without changing the first and
the last line.
Loading the editor…
Exercise · Write the code
Write a tidy task line
A task was typed as " call the dentist ". Make two more boxes:
task, the name with no end spaces and a capital first
letter;
size, how many characters task has.
Then print this line, with a template string:
text
Added: Call the dentist (16 characters)
Loading the editor…
Recap
Recap · 3 questions
Check yourself
task holds " Buy milk ". What is in it after task.trim();?
Check yourself
Which line gives the number of characters in task?
Check yourself
What type of value does task.includes("milk") give?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Working with strings: common methods
What things are
Word
What it means
Method
A command that belongs to a value: task.trim()
Property
A fact a value carries, read without brackets
length
How many characters a string has, spaces included
Index
A character's place in a string, counted from 0
Chaining
Calling methods one after another: .trim().toUpperCase()
Make a new string
Write
To
task.trim()
Remove the spaces and tabs at both ends
task.toUpperCase()
Turn every letter into a capital
task.toLowerCase()
Make every letter lower case
task.slice(0, 3)
Cut indexes 0 to 2 out of it
task.slice(4)
Cut from index 4 to the end
task.replace("a", "b")
Replace the first "a" with "b"
task.replaceAll("a", "b")
Replace every "a" with "b"
Measure and ask
Write
To
task.length
Count its characters
task.includes("milk")
Ask whether "milk" is in it
task.startsWith("Buy")
Ask whether it begins with "Buy"
task.endsWith("milk")
Ask whether it ends with "milk"
task.indexOf("milk")
Find where "milk" starts, or -1
Rules
Rule
What it means
Never changed
A method gives back a new string; the old one stays
Keep the answer
const tidy = task.trim();, never task.trim(); alone
From 0
The first character has index 0, the last length - 1
Stop before
slice(0, 3) stops before index 3
Capitals count
"Milk" is not "milk"; lower-case both to ignore it
Brackets
A method has them, even empty; a property never does
TS2551, TS2339
No such name after the dot: check its capitals
Where to go next
You can now measure a string, ask whether it contains, starts or
ends with a piece of text, find where that piece starts, cut
pieces out, and make tidy copies, one method or a whole chain at
a time. Above all, you keep the copy each method gives back,
because the string you started with never changes. TaskKit tidies
its task names before it prints them.
Next is Number pitfalls: NaN, floating point, and Math.
Strings have their surprises in capitals and positions; numbers
have theirs too: a sum that comes out as 0.30000000000000004,
and a value that says it is a number but is "not a number". The
next lesson explains both, and the Math tools that round and
compare numbers safely.
Before you move on, make TaskKit cope with a shouted name. Type the
second task as " CALL THE DENTIST " and run it: the second
Added: line says Added: CALL THE DENTIST. Change the line that
builds secondTask so the rest of the name is made lower case too,
and it prints Call the dentist again. Check it and run it before
you call it done.