Skip to content

Chapter 05

Working with Text

Strings show up everywhere: names, messages, addresses, the words on this page. Let's learn how to build and manipulate them.

Joining Strings Together

You can glue strings together with +. When used with text, + means "join," not "add":

const firstName = "Ada";
const lastName = "Lovelace";
const fullName = firstName + " " + lastName;
console.log(fullName); // Ada Lovelace

Notice the " " - a string containing a single space - so the two names don't end up stuck together. Every space and comma you want must be written explicitly.

A Cleaner Way: Template Literals

All those quotes and plus signs get messy fast. There's a nicer way. If you wrap a string in backticks ` ` (the key above Tab, left of 1), you can drop variables straight inside using ${ }:

const name = "Ada";
const age = 36;

const message = `${name} is ${age} years old`;
console.log(message); // Ada is 36 years old

This is called a template literal. Everything inside ${ } is worked out and dropped into the text. It reads much more clearly than joining with +, and it's what you'll use most of the time.

Tip
Backticks also let a string span multiple lines, which regular quotes can't do. Handy for longer messages.

The Classic Trap: Numbers as Text

Because + both adds numbers and joins strings, mixing them causes the single most common beginner surprise:

console.log(5 + 3);       // 8   - two numbers, added
console.log("5" + "3");   // "53" - two strings, joined
console.log("5" + 3);     // "53" - one is text, so JS joins!

When one side of + is a string, JavaScript turns the other side into text and joins them. This bites you when numbers arrive as text - for example, anything a user types into a form is a string, even "42". Convert text to a number first with Number(...):

const typed = "5";           // came in as text
console.log(Number(typed) + 3); // 8 - now it's a real number

Asking a String to Do Things

Strings come with built-in abilities called methods. You use one by writing a dot after the string, the method's name, and brackets. A few you'll reach for often:

const word = "JavaScript";

console.log(word.length);        // 10   - how many characters (no brackets!)
console.log(word.toUpperCase()); // "JAVASCRIPT"
console.log(word.toLowerCase()); // "javascript"
console.log(word.includes("Script")); // true - does it contain this?
console.log(word.replace("Java", "Type")); // "TypeScript"

length is special - it's a piece of information, not an action, so it has no brackets. The rest are actions, so they do.

Note
Methods never change the original string - they hand back a new one. word is still "JavaScript" after all of the above. If you want to keep a result, store it in a variable.