Skip to content
Educora
Beginner13 min4 / 27

Strings and template literals

Learn to work with text: accessing characters, useful methods and template literals that put variables into text with ease.

Check yourself
In this lesson you will learn
  • Find a string's length and access a character by its index
  • Use methods such as trim, includes, slice and split
  • Put variables and expressions into text with template literals

Your phone shows the message “Hi, Aysel! You have 3 new messages”. The program doesn't store this sentence ready-made — it builds it from pieces: fixed words, the user's name and the number of messages. Working with text is one of the most common jobs in programming.

Creating strings

A string is a sequence of characters. You can write it in single quotes, double quotes or between backticks. Single and double quotes work the same; the only rule is that the opening and closing quote must match. Inside a string the \ sign is used for special characters: \n means a new line and \' means a quote character.

JavaScript
const single = 'Hello';
const double = "Hello";
const quote = 'It\'s JavaScript';

console.log(single, double);
console.log(quote);
console.log('Line 1\nLine 2');
▸ Expected output
Hello Hello
It's JavaScript
Line 1
Line 2

Length and indexes

The length property tells you how many characters a string has. Each character has its own number — an index — and counting starts from 0. So in 'Baku' the B is at index 0 and the u at index 3. You can also get the last character with at(-1).

JavaScript
const city = 'Baku';

console.log(city.length);
console.log(city[0]);
console.log(city[city.length - 1]);
console.log(city.at(-1));
console.log(city.toUpperCase());
console.log(city.toLowerCase());
▸ Expected output
4
B
u
u
BAKU
baku

Useful methods

A method is a function “attached” to a value, and you call it with a dot: city.toUpperCase(). Strings have many methods, but the ones below cover most everyday tasks.

MethodWhat it doesExample
trim()removes spaces at the start and end' hi '.trim() → 'hi'
includes(x)checks whether the string contains x'cat'.includes('a') → true
indexOf(x)returns the first index of x, or −1'cat'.indexOf('t') → 2
slice(a, b)cuts out the part from a up to b (not including b)'Hello'.slice(1, 3) → 'el'
replace(a, b)replaces the first a with b'hi'.replace('h', 'H') → 'Hi'
split(x)splits the string at x and returns an array'a-b'.split('-') → ['a', 'b']
JavaScript
const email = '  Leyla.Mammadova@Example.com  ';
const clean = email.trim().toLowerCase();

console.log(clean);
console.log(clean.includes('@'));
console.log(clean.indexOf('@'));
console.log(clean.slice(0, clean.indexOf('@')));
console.log(clean.endsWith('.com'));
▸ Expected output
leyla.mammadova@example.com
true
15
leyla.mammadova
true
Methods can be chained: first trim(), then toLowerCase().
JavaScript
const sentence = 'I love JavaScript';

console.log(sentence.replace('love', 'enjoy'));
console.log(sentence.split(' '));
console.log('ha'.repeat(3));
console.log('7'.padStart(3, '0'));
console.log(sentence);
▸ Expected output
I enjoy JavaScript
[ 'I', 'love', 'JavaScript' ]
hahaha
007
I love JavaScript

Template literals

Gluing text together piece by piece with + is tiring, and it's easy to forget a space. Template literals make it easier. They are written between backticks — on a US English keyboard this key is right below Esc. When you write ${...} inside, the value of the expression in the braces is put into the text.

JavaScript
const name = 'Aysel';
const messages = 3;

console.log('Hi, ' + name + '! You have ' + messages + ' new messages.');
console.log(`Hi, ${name}! You have ${messages} new messages.`);
▸ Expected output
Hi, Aysel! You have 3 new messages.
Hi, Aysel! You have 3 new messages.
The result is the same, but the second line is much easier to read and write.

Inside ${...} you can put any expression, not just a variable: a calculation or a method call. Template literals can also span several lines — no need to write \n. The toFixed(2) method shows a number with two digits after the decimal point.

JavaScript
const item = 'bread';
const price = 0.8;
const quantity = 5;

console.log(`Total: ${price * quantity} AZN`);

const receipt = `Item: ${item.toUpperCase()}
Quantity: ${quantity}
Sum: ${(price * quantity).toFixed(2)} AZN`;
console.log(receipt);
▸ Expected output
Total: 4 AZN
Item: BREAD
Quantity: 5
Sum: 4.00 AZN
JavaScript
const name = 'Elvin';

console.log('Hi, ${name}');
console.log(`Hi, ${name}`);
▸ Expected output
Hi, ${name}
Hi, Elvin

Practice: building a username

Let's combine what we have learned. We build a username from a full name: split(' ') separates the first and last name, toLowerCase() makes the letters small, and a template literal joins the parts with a dot. Try the code with your own name.

JavaScript
const fullName = 'Murad Aliyev';
const parts = fullName.split(' ');
const login = `${parts[0].toLowerCase()}.${parts[1].toLowerCase()}`;

console.log(parts);
console.log(login);
console.log(`Welcome, ${parts[0]}! Your login is ${login}`);
▸ Expected output
[ 'Murad', 'Aliyev' ]
murad.aliyev
Welcome, Murad! Your login is murad.aliyev
Exercise

The name in the form is messy: ' Leyla HASANOVA '. Build the login leyla.hasanova12 from it (the last two digits of the birth year go at the end) and print it. Then print the login's length as Login length: N.

Exercise · JavaScript
const rawName = '  Leyla HASANOVA ';
const year = 2012;
// 1) build and print the login leyla.hasanova12
// 2) print Login length: N
▸ Expected output
leyla.hasanova12
Login length: 16

Key points

  • A string is written in single quotes, double quotes or backticks; \n means a new line.
  • length gives the number of characters; indexes start at 0.
  • trim, includes, slice, replace and split are the most used methods.
  • String methods don't change the original; they return a new string.
  • In template literals ${...} puts an expression's value into the text, and it works only in backticks.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What is 'JavaScript'.length?