JavaScript Strings

Text in quotes, joining strings, template literals and special characters.

Lesson 7 of 56Beginner13 min read

A string is a piece of text: a name, a message, a password or even an emoji. Strings are probably the data type you'll use most, because so much of what a website shows is text built from data.

In this lesson you'll learn the three ways to write strings, how to read individual characters, and how to build text from variables. Modern JavaScript has an excellent feature for that last job called template literals, and once you start using them you'll rarely go back.

Three kinds of quotes

JavaScript
const a = "double quotes";
const b = 'single quotes';
const c = `backticks`;

Single and double quotes work in exactly the same way, so pick one style and use it consistently. Backticks are special, as you'll see below. If your text contains one kind of quote, wrap it in the other: "It's sunny".

String length and individual characters

  • text.length gives the number of characters, so "cat".length is 3.
  • text[0] gives the first character. Counting starts at 0, not 1.
  • text[text.length - 1] gives the last character.
  • text.at(-1) also gives the last character, in a shorter modern form.

Strings are immutable, which means you can't change a single character in place. String methods always return a new string and leave the original unchanged. To keep the result, store it in a variable.

Joining strings: concatenation and template literals

The older way to join strings uses +, which is called concatenation:

JavaScript
"Hello, " + name + "! You have " + count + " messages."

The modern way uses template literals, which are backticks with ${ } placeholders:

JavaScript
`Hello, ${name}! You have ${count} messages.`

Anything inside ${ } is worked out first, whether it's a variable, a sum or a function call. Template literals can also span multiple lines, which makes them handy for building small pieces of HTML.

Escape characters

WriteGives
\nA new line
\tA tab
\" / \'A quote inside the same kind of quotes
\\A backslash

The backslash tells JavaScript that the next character has a special meaning. Inside template literals you rarely need escapes, because both kinds of quote can be used freely.

Strings can't be changed in place

Strings are immutable: once created, their characters can't be changed. Writing name[0] = "J" does nothing. Every string method, such as toUpperCase() or replace(), returns a new string and leaves the original as it was, so you need to save the result: name = name.toUpperCase().

Strings can also be compared with ===, which checks every character, including capitals and spaces. That's why "Hello" === "hello" is false, and why user input is often cleaned with trim() and toLowerCase() before checking it. You'll find all the most useful methods in the string methods lesson.

JavaScript Strings Syntax

String basics

const s = "Pixel";
s.length;            // 5
s[0];                // "P"
`Hi ${s}!`;          // "Hi Pixel!"
"Line 1\nLine 2";    // two lines

JavaScript Strings Summary

  • Strings hold text and can use single quotes, double quotes or backticks.
  • length gives the number of characters, and text[0] reads the first one.
  • Strings are immutable; methods return new strings.
  • Template literals use backticks and ${ } to insert values.
  • Escape characters such as \n and \" add special characters.

JavaScript Strings Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Length and characters

const word = "JavaScript";

console.log(word.length);
console.log(word[0]);
console.log(word[4]);
console.log(word[word.length - 1]);
console.log(word.at(-1));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 310 characters.
  2. Line 4Index 0 is the first character, "J".
  3. Line 5Index 4 is the fifth character, "S".
  4. Lines 6 to 7Two ways to get the last character, "t".
Example 2

Template literals vs +

const customer = "Zara";
const items = 3;
const price = 4.5;

const old = "Hi " + customer + ", your " + items + " items cost £" + items * price + ".";
const modern = `Hi ${customer}, your ${items} items cost £${items * price}.`;

console.log(old);
console.log(modern);

const card = `🎟  Ticket
   Name: ${customer}
   Seat: ${items}A`;
console.log(card);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 5Concatenation: lots of + and easy-to-miss spaces.
  2. Line 6Same result with a template literal. Maths works inside ${ }.
  3. Lines 11 to 14Template literals keep line breaks, so multi-line text is easy.
Example 3

Quotes and escapes

console.log("She said \"hello\"");
console.log('It\'s a sunny day');
console.log("It's easier to mix quotes");
console.log("Path: C:\\Users\\Sam");
console.log("Name:\tPixel\nType:\tCat");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 2A backslash lets you use the same quote inside.
  2. Line 3Or simply use the other kind of quote.
  3. Line 4\\ gives one backslash.
  4. Line 5\t is a tab and \n a new line.

Common JavaScript Strings Mistakes

Using ${} inside normal quotes

Don't
const msg = "Hello ${name}"; // prints literally: Hello ${name}
Do
const msg = `Hello ${name}`;

Placeholders only work inside backticks.

Mismatched quotes

Don't
const s = "Hello';
Do
const s = "Hello";

A string must start and end with the same kind of quote.

Forgetting index starts at 0

Don't
const first = "cat"[1]; // "a"
Do
const first = "cat"[0]; // "c"

JavaScript Strings in Real Projects

Strings in apps

Notifications ("Sam liked your photo"), receipts, error messages, URLs, search queries and chat messages are all strings built from variables. Template literals are used everywhere for this, and even for generating HTML, as you'll see in DOM Manipulation.

JavaScript Strings Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Build the greeting with a template literal.

const user = "Kai";
const msg = Welcome back, !;
console.log(msg);
Predict the outputeasy

What does this print?

const city = "Paris";
console.log(city.length, city[1]);
Multiple choicemedium

Which kind of quotes makes ${5 * 3} turn into 15?

Fix the bugmedium

The message should read Mia has 3 new messages. Fix it using a template literal.

const person = "Mia";
const count = 3;
const message = "${person} has ${count} new messages";
console.log(message);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Mia has 3 new messages"

JavaScript Strings Quiz

3 questions to check what you learned.

  1. What is "hello".length?

    • 4
    • 6
    • 5
    • "hello"
  2. Which quote type allows ${variables} and multiple lines?

    • "double"
    • 'single'
    • backticks
    • All of them
  3. What does "\n" represent?

    • The letter n
    • A new line
    • A null value
    • A tab

JavaScript Strings Challenge

Build a profile card string

Using the variables, create a constant card with a template literal so that console.log(card) prints exactly:

Luna (12) loves skateboarding

Then log the first letter of hobby using an index, and the length of nameText.

const nameText = "Luna";
const age = 12;
const hobby = "skateboarding";
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • card is correct
  • Logs the card
  • Logs the first letter "s"
  • Logs the length 4