Lesson 7 of 28
Working with Text
Strings, template literals, and the methods you actually use — plus why .toUpperCase() never changes the original text and why indexes start at zero.
Most of what a person sees on screen is text: a lesson title, a price, a name in the corner. In JavaScript a piece of text is called a string, and you will handle strings more often than any other kind of value.
Quotes come in three flavours
Single and double quotes do exactly the same job. Neither is more correct.
const single = 'Working with Text';
const double = "Working with Text";Those two produce identical strings. Teams pick one and stay consistent, and that is the whole of the convention. The only time the choice matters is when the text itself contains a quote:
const broken = 'It's ready'; // SyntaxError
const fine = "It's ready"; // no problem
const escaped = 'It\'s ready'; // also fineThe apostrophe in the first line closes the string early, and the rest of the line stops making sense to JavaScript. A backslash before a character is called an escape: it tells JavaScript to treat the next character as plain text rather than as punctuation. Easier still, use the quote style that does not appear in your text.
Template literals are the modern default
The third flavour is the backtick, and it can do something the other two
cannot: drop a value straight into the middle of some text using ${}.
const name = "Anish";
const minutes = 9;
const line = `${name} has ${minutes} minutes left`;
// "Anish has 9 minutes left"Anything inside ${} is real JavaScript. It gets worked out first, then turned
into text:
const price = 199;
console.log(`Total: ${price * 3} rupees`); // Total: 597 rupeesBacktick strings can also run across several lines, which the other two cannot:
const summary = `Lesson: Functions
Minutes: 9`;Reach for backticks by default. They cost nothing when you are not using ${},
and they save you from rewriting the line the moment you need to insert a
value.
Joining text with plus
Before template literals, you glued text together with +:
const greeting = "Hello, " + name + ". You have " + minutes + " minutes.";That still works, and you will read plenty of code written this way. Compare it to the backtick version and you can see why the newer style won:
const greeting = `Hello, ${name}. You have ${minutes} minutes.`;One thing worth noticing: "Total: " + 199 gives you "Total: 199". When +
has a string on one side, it converts the other side to text. Handy here, and a
source of real bugs elsewhere — the Numbers lesson comes back to it.
Length, and reading a single character
.length counts the characters, spaces included:
"Functions".length; // 9
"a b".length; // 3
"".length; // 0You read one character with square brackets and a number:
const title = "Arrays";
title[0]; // "A"
title[1]; // "r"Almost everyone finds it odd that the first character is 0 rather than 1.
It helps to stop reading the number as "which character" and start reading it
as "how far from the start". The first character is zero steps in. The second
is one step in. Counting that way, the last character of a six-letter word sits
at index 5, which is length - 1.
title[title.length - 1]; // "s"
title[title.length]; // undefined — one past the end
title.at(-1); // "s" — the shortcutThat undefined is the dangerous part. Reading past the end is not an error,
so an off-by-one mistake produces no warning at all. It just quietly hands you
nothing.
The methods you will actually use
There are dozens. These seven cover the vast majority of real code.
const raw = " Learn JavaScript ";
raw.trim(); // "Learn JavaScript" — strips outer whitespace
raw.trim().toUpperCase(); // "LEARN JAVASCRIPT"
"ANISH".toLowerCase(); // "anish"const title = "Working with Text";
title.includes("Text"); // true — is this bit in there?
title.replace("Text", "Words"); // "Working with Words"
title.split(" "); // ["Working", "with", "Text"]
title.slice(0, 7); // "Working" — from index 0 up to, not including, 7
title.slice(-4); // "Text" — the last four characterssplit is how you turn one string into a list you can loop over. slice takes
a start index and an optional end index, and the end is not included — the same
"how far from the start" counting as before.
replace only changes the first match, which surprises people:
"cat cat".replace("cat", "dog"); // "dog cat"
"cat cat".replaceAll("cat", "dog"); // "dog dog"Comparisons and includes are case sensitive, so a search box that is meant to
be forgiving usually lowercases both sides first:
const query = "JAVA";
title.toLowerCase().includes(query.toLowerCase()); // false, but reliably soStrings never change
This is the one that catches everybody at least once.
let name = " anish ";
name.trim();
console.log(name); // " anish " — still paddedNothing is broken. Strings in JavaScript are immutable, which means a string
value can never be edited once it exists. Every method you call gives back a
brand new string and leaves the original exactly as it was. name.trim()
produced a clean string and then threw it away, because nothing caught it.
name = name.trim();
console.log(name); // "anish"Keep this in mind whenever a string method looks like it did nothing. Nine times out of ten, it worked perfectly and you forgot to keep the result.
Try it yourself
Change the raw name, then add a line that checks whether the trimmed name
includes "law".
What to remember
- Single and double quotes are interchangeable; backticks with
${}are the default worth reaching for. - Indexes count steps from the start, so the first character is
0and the last islength - 1. replacechanges the first match only —replaceAllchanges all of them.- Strings are immutable. Methods return a new string, so you have to keep it.
Check yourself
4 questions · pass 3/4 to unlock Numbers and Maths
1.A learner writes
let name = " anish ";then callsname.trim()and logsname. The spaces are still there. Why?2.Given
const title = "Arrays";which expression gives you the last character?3.Why does
const line = 'It's ready';fail?4.What does
"cat cat cat".replace("cat", "dog")give you?
4 left to answer