Skip to content

Beginner · Strings, decisions and loops · topic 6 of 61 · 25 min

Strings and template literals

Explanation

A string is text inside quotes. Template literals, written with backticks, let you put values inside text with ${...} and span many lines. Strings never change; methods like toUpperCase, slice, trim and split return NEW strings.

Three ways to write a string

A string is a sequence of characters: letters, digits, spaces, emoji. You can write it with single quotes, double quotes or backticks. Single and double quotes work the same. Backticks make a template literal, which can hold placeholders and line breaks.

javascript
const city = 'Pune';
const state = "Maharashtra";
const line = `${city} is in ${state}`;
console.log(line);        // Pune is in Maharashtra
const address = `Flat 4B
MG Road`;
console.log(address);     // two lines

Inside a placeholder ${...} you can write any expression: `Total: ${price * qty}`. This is much easier to read than joining pieces with +.

Escape characters

A backslash starts an escape: \n is a new line, \t a tab, \' a quote inside single quotes, and \\ a real backslash. Windows file paths like C:\\Users need double backslashes inside normal strings.

Length and characters

javascript
const word = 'Namaste';
console.log(word.length);  // 7
console.log(word[0]);      // 'N'
console.log(word.at(-1));  // 'e' (at() accepts negative positions)
console.log(word[10]);     // undefined (no error)

Strings are immutable

Immutable means it cannot be changed. word[0] = 'n' silently does nothing. Every string method gives you a new string and leaves the original as it was. So you must store the result.

javascript
let name = '  asha  ';
name.trim();             // result thrown away!
console.log(name);       // '  asha  '
name = name.trim().toUpperCase();
console.log(name);       // 'ASHA'
Careful: A very common bug is calling a string method and not using the result: text.trim(); on its own line does nothing useful. Write text = text.trim(); or use the result directly.

The methods you will use every day

MethodExampleResult
slice(start, end)'Bengaluru'.slice(0, 4)'Beng' (end not included)
toUpperCase / toLowerCase'upi'.toUpperCase()'UPI'
trim' hi '.trim()'hi'
includes'order-123'.includes('123')true
startsWith / endsWith'photo.jpg'.endsWith('.jpg')true
indexOf'banana'.indexOf('n')2 (or -1 if missing)
split'a,b,c'.split(',')['a', 'b', 'c']
replaceAll'1-800-123'.replaceAll('-', '')'1800123'
padStart'7'.padStart(3, '0')'007'
repeat'ab'.repeat(3)'ababab'

slice also accepts negative numbers: 'invoice.pdf'.slice(-3) is 'pdf'. replace changes only the first match unless you use replaceAll (or a regular expression with the g flag, module 7).

Comparing strings

=== compares strings exactly, including capital letters: 'Delhi' === 'delhi' is false. Compare in one case: a.toLowerCase() === b.toLowerCase(). < and > compare character codes, so 'Z' < 'a' is true. To sort names the way people expect, use a.localeCompare(b).

Tip: Build long messages with template literals, and clean up user input with trim() before checking it. Most "the login does not work" bugs are an extra space.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Strings and template literals · 1/6

Strings

In this lesson you will work with text, which JavaScript calls strings.

Prefer a video by a teacher? Find free videos on “javascript string methods template literals tutorial” on YouTube ↗

In real life: Masking a card number on a payment page

Payment pages never show the full card number. They keep only the last four digits and replace the rest with stars. This uses slice, padStart and a template literal.

javascript
const card = '4111222233334444';
const last4 = card.slice(-4);
const masked = last4.padStart(card.length, '*');
console.log(`Paying with card ${masked}`);
Prints Paying with card ************4444.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function initials(fullName) that returns the first letter of the first and last word in capitals. Example: initials("asha rao") returns "AR".

Task 2 · Code · Javascript

Write a function maskPhone(phone) for a 10-digit mobile number string. Keep the first 2 and last 2 digits and replace the middle 6 with "x". Example: maskPhone("9876543210") returns "98xxxxxx10".

Task 3 · Code · Javascript

Write a function receiptLine(item, qty, price) that returns a template-literal line like "Chai x 3 = Rs 45" where the total is qty * price.

Quick quiz

Question 1

1.What is 'Bengaluru'.slice(0, 4)?

Question 2

2.let s = 'hi'; s.toUpperCase(); console.log(s); What is printed?

Question 3

3.What is '7'.padStart(3, '0')?

Question 4

4.What does 'a,b,,c'.split(',') give?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is 'Bengaluru'.slice(0, 4)?

Answer: 'Beng'

slice takes characters from index 0 up to, but not including, index 4.

let s = 'hi'; s.toUpperCase(); console.log(s); What is printed?

Answer: 'hi'

Strings are immutable; the result of toUpperCase was thrown away.

What is '7'.padStart(3, '0')?

Answer: '007'

padStart adds characters at the start until the length is 3.

What does 'a,b,,c'.split(',') give?

Answer: ['a', 'b', '', 'c']

Two commas in a row make an empty string between them.

Which gives the last character of the string text?Related

Answer: text.at(-1)

at(-1) counts from the end. text[-1] is undefined, there is no last() method, and slice(0, 1) gives the first character.

From Strings in depth

What does immutable mean for strings?Related

Answer: Once made, a string's characters cannot change; methods return new strings

Every "change" creates a new string.

From Strings: methods, interpolation, verbatim and raw strings

How many bytes does "UPI" occupy as a string literal?Related

Answer: 4

3 letters + the terminator.

From Strings are char arrays

How should you compare two Strings for equal text?Related

Answer: a.equals(b)

equals compares content.

From Strings in depth

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Strings, decisions and loops” before its exam: Decisions with if and else, switch, the ternary operator and lookup tables, Loops: for, while, do…while, for…of and for…in, Loop patterns that solve real problems.
  2. Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and closures. 61 topics left in the course before the final exam.

← Previous: Numbers and Math