Beginner · Strings, decisions and loops · topic 6 of 61 · 25 min
Strings and template literals
Explanation
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.
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 linesInside 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
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.
let name = ' asha ';
name.trim(); // result thrown away!
console.log(name); // ' asha '
name = name.trim().toUpperCase();
console.log(name); // 'ASHA'The methods you will use every day
| Method | Example | Result |
|---|---|---|
| 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).
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
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.
const card = '4111222233334444';
const last4 = card.slice(-4);
const masked = last4.padStart(card.length, '*');
console.log(`Paying with card ${masked}`);Practice (0/3 done)
Write a function initials(fullName) that returns the first letter of the first and last word in capitals. Example: initials("asha rao") returns "AR".
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".
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Decisions with if and elseStrings, decisions and loops · same module
- switch, the ternary operator and lookup tablesStrings, decisions and loops · same module
- Loops: for, while, do…while, for…of and for…inStrings, decisions and loops · same module
- Strings in depthFrontend Web Development · JavaScript in depth
- Strings: methods, interpolation, verbatim and raw stringsC# and .NET · Arrays, strings and null
- Strings are char arraysC Programming (from zero to systems) · Strings in C
Questions people ask about this
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
How should you compare two Strings for equal text?Related
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
- 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.
- Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and closures. 61 topics left in the course before the final exam.