JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects
Template Literals and String Methods
In this lesson8
Every hour the Jurassic Park lab produces reports: species, weight, zone, health status. Gluing them together with pluses quickly turns into a thicket of quotes, and sensor data arrives with extra spaces and random letter case. Template literals and string methods are the tools that put text in order: from inserting variables to searching and transforming strings.
Template Literals - Basics
Template literals are strings wrapped in backticks, the reversed apostrophes, instead of ordinary quotes. You insert a JavaScript expression into them with the ${...} syntax:
const species = 'T-Rex';
const weight = 8000;
// The old way - concatenation
const old = 'Species: ' + species + ', weight: ' + weight + ' kg';
// Template literal - much more readable!
const report = `Species: ${species}, weight: ${weight} kg`;
console.log(report); // "Species: T-Rex, weight: 8000 kg"Both variables hold the same text, but in the template you can see the shape of the sentence at a glance. That is why I recommend template literals whenever the text contains even one variable.
Expressions Inside ${}
Inside ${} you can place any JavaScript expression, not just a variable. The conditional operator, arithmetic, method calls and even a nested template literal all work here:
const dino = { name: 'Rex', health: 85 };
console.log(`Status: ${dino.health > 50 ? 'stable' : 'critical'}`);
// "Status: stable"
console.log(`Health: ${dino.health}%`);
// "Health: 85%"
console.log(`Double dose: ${dino.health * 2} units`);
// "Double dose: 170 units"
console.log(`Name: ${dino.name.toUpperCase()}`);
// "Name: REX"JavaScript first evaluates the expression, then turns the result into text and pastes it in place of ${}. The dino object stays untouched.
Multi-line Strings
Template literals keep multi-line formatting, so you do not need to insert \n:
const dinoCard = `
ββββββββββββββββββββββββββ
β Species: T-Rex β
β Zone: A β
β Status: Active β
ββββββββββββββββββββββββββ
`;
console.log(dinoCard);Every line break and every space inside the backticks ends up in the result, including the empty line at the start.
Tagged Templates
Tagged templates let you process a template with a function. The "tag" function receives an array of the fixed text fragments and the values of the expressions, and there is always one more fragment than there are values:
function highlight(strings, ...values) {
let result = '';
strings.forEach((str, i) => {
result += str;
if (i < values.length) {
result += '**' + values[i] + '**';
}
});
return result;
}
const name = 'Rex';
const zone = 'A';
const tagged = highlight`Dinosaur ${name} in zone ${zone}`;
console.log(tagged);
// "Dinosaur **Rex** in zone **A**"Notice that the tag is called without parentheses: the function name sits right before the backtick. A practical use is building database queries in which the values travel separately from the query text:
function sql(strings, ...values) {
const query = strings.join('?');
return { query, params: values };
}
const zoneId = 'A';
const minHealth = 80;
const query = sql`SELECT * FROM dinos WHERE zone = ${zoneId} AND health > ${minHealth}`;
// { query: "SELECT * FROM dinos WHERE zone = ? AND health > ?", params: ['A', 80] }The values were not pasted into the query text; they were set aside in params. Parameterized queries work on this principle, and they protect the database from SQL injection attacks.
String Methods - Searching
Let us start with searching for fragments in a DNA sequence. Each of these methods only reads the text and returns an answer:
const dnaSequence = 'ATCG-TTGA-ACGT-TTGA';
// indexOf() - returns the index of the first occurrence (or -1)
console.log(dnaSequence.indexOf('TTGA')); // 5
console.log(dnaSequence.indexOf('XXXX')); // -1
console.log(dnaSequence.lastIndexOf('TTGA')); // 15 - the last occurrence
// includes() - checks whether the string contains a fragment (boolean)
console.log(dnaSequence.includes('ACGT')); // true
console.log(dnaSequence.includes('ZZZZ')); // false
// startsWith() / endsWith() - checks the start/end
console.log(dnaSequence.startsWith('ATCG')); // true
console.log(dnaSequence.endsWith('TTGA')); // true
console.log(dnaSequence.startsWith('TTGA', 5)); // true - from position 5
// match() with a regular expression - all matches
console.log(dnaSequence.match(/TTGA/g)); // ['TTGA', 'TTGA']All of these methods are case-sensitive, so includes('acgt') returns false. When you only ask "is it there?", choose includes(), because it reads like a sentence, and keep indexOf() for when you need the position.
String Methods - Extracting and Splitting
Extracting comes in handy when you need only part of a specimen's full name:
const specimen = 'Tyrannosaurus Rex';
// slice(start, end) - extracts a fragment of the string
console.log(specimen.slice(0, 13)); // "Tyrannosaurus"
console.log(specimen.slice(14)); // "Rex"
console.log(specimen.slice(-3)); // "Rex" (from the end)
// split() - splits the string into an array
const zones = 'A-B-C-D'.split('-');
console.log(zones); // ['A', 'B', 'C', 'D']
const words = 'Jurassic Park is great'.split(' ');
console.log(words); // ['Jurassic', 'Park', 'is', 'great']slice does not include the character at index end, and a negative index counts from the end, so slice(-3) gives the last three characters. split returns an array, which you will unpack with destructuring in the next lesson.
String Methods - Transformations
Raw sensor data needs cleaning. The key rule: strings are immutable, so every method returns a new string:
const dinoName = ' velociraptor ';
// trim() - removes whitespace from the start and end
console.log(dinoName.trim()); // "velociraptor"
console.log(dinoName.trimStart()); // "velociraptor "
console.log(dinoName.trimEnd()); // " velociraptor"
// toUpperCase() / toLowerCase()
console.log('rex'.toUpperCase()); // "REX"
console.log('T-REX'.toLowerCase()); // "t-rex"
// replace() - replaces the first occurrence
const text = 'Zone A, Zone B, Zone A';
console.log(text.replace('Zone', 'Sector')); // "Sector A, Zone B, Zone A"
// replaceAll() - replaces all occurrences
console.log(text.replaceAll('Zone', 'Sector')); // "Sector A, Sector B, Sector A"After these calls dinoName still has its spaces and text still contains "Zone". Store the result in a new variable if you want to keep it. So the difference between replace and replaceAll is the number of replacements, not whether the original changes.
String Methods - Padding
The padStart() and padEnd() methods pad a string to a given length, and repeat() copies it. Together they let you align a table of specimens:
// padStart(length, fillString) - pads from the start
const dinoId = '42';
console.log(dinoId.padStart(5, '0')); // "00042"
console.log(dinoId.padStart(5, '-')); // "---42"
// padEnd(length, fillString) - pads from the end
const label = 'Rex';
console.log(label.padEnd(10, '.')); // "Rex......."
// repeat(count) - repeats the string
console.log('-'.repeat(30)); // "------------------------------"
// A practical example - formatting a table
const specimens = [
{ id: '1', name: 'T-Rex' },
{ id: '42', name: 'Velociraptor' },
{ id: '100', name: 'Triceratops' }
];
specimens.forEach(s => {
const formattedId = s.id.padStart(4, '0');
const formattedName = s.name.padEnd(15, ' ');
console.log(`ID: ${formattedId} | Species: ${formattedName}`);
});
// ID: 0001 | Species: T-Rex
// ID: 0042 | Species: Velociraptor
// ID: 0100 | Species: TriceratopsThe first argument is the target length of the whole string, not the number of characters to add. That is why '42'.padStart(5, '0') adds three zeros.
Method Chaining
String methods can be chained, because each one returns a new string on which you call the next:
const messy = ' jurassic PARK is GREAT ';
const clean = messy.trim().toLowerCase().replace(/\s+/g, ' ');
console.log(clean); // "jurassic park is great"
const dinoCode = 'trex-001';
const formatted = dinoCode.split('-')
.map(part => part.toUpperCase())
.join('-');
console.log(formatted); // "TREX-001"/\s+/g is a regular expression meaning any run of whitespace characters, and the g flag replaces all occurrences. The same pattern creates friendly report addresses:
function formatReport(rawInput) {
return rawInput
.trim()
.toLowerCase()
.replace(/\s+/g, '-') // spaces to hyphens
.replace(/[^a-z0-9-]/g, '') // remove anything other than letters, digits and hyphens
.slice(0, 50); // max 50 characters
}
console.log(formatReport(' T-Rex Escape!! Zone A '));
// "t-rex-escape-zone-a"Each step of the chain does one thing, so it is easy to read and fix. I recommend breaking long chains the way it is done here, one method per line.
Practice
The sandbox contains report templates, DNA searching, slice, split, replace and padding. Change the arguments and predict the result before you run the code.
Code for this lesson: index.js
// === TEMPLATE LITERALS AND STRING METHODS ===
// 1. Template literals - inserting expressions
const species = 'T-Rex';
const weight = 8000;
console.log('=== Template Literals ===');
console.log(`Species: ${species}, weight: ${weight} kg`);
console.log(`Health: ${weight > 5000 ? 'large specimen' : 'small specimen'}`);
console.log(`Double dose: ${weight * 0.05} kg`);
// 2. Multiline strings
const card = `
=== DINOSAUR CARD ===
Species: ${species}
Weight: ${weight} kg
Status: active
`;
console.log(card);
// 3. Search methods
console.log('=== Searching ===');
const dna = 'ATCG-TTGA-ACGT-TTGA';
console.log('indexOf TTGA:', dna.indexOf('TTGA'));
console.log('includes ACGT:', dna.includes('ACGT'));
console.log('startsWith ATCG:', dna.startsWith('ATCG'));
console.log('endsWith TTGA:', dna.endsWith('TTGA'));
// 4. Slicing and splitting
console.log('\n=== Slice and Split ===');
const specimen = 'Tyrannosaurus Rex';
console.log('slice(0,13):', specimen.slice(0, 13));
console.log('slice(-3):', specimen.slice(-3));
console.log('split:', 'A-B-C-D'.split('-'));
// 5. Transformations
console.log('\n=== Transformations ===');
console.log('trim:', ' rex '.trim());
console.log('toUpperCase:', 'rex'.toUpperCase());
console.log('replace:', 'Zone A, Zone B'.replace('Zone', 'Area'));
console.log('replaceAll:', 'Zone A, Zone B'.replaceAll('Zone', 'Area'));
// 6. Padding
console.log('\n=== Padding ===');
console.log('padStart:', '42'.padStart(5, '0'));
console.log('padEnd:', 'Rex'.padEnd(10, '.'));
// 7. Method chaining
console.log('\n=== Chaining ===');
const messy = ' JURASSIC park ';
const clean = messy.trim().toLowerCase();
console.log('Result:', clean);Remember: a template literal is a label with blank fields for data, and string methods are the lab assistant's scalpels, which never cut the original sample but always make a copy.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What character do we use to surround template literals in JavaScript?
2. What syntax allows you to insert a JavaScript expression inside a template literal?
3. What will 'Tyrannosaurus Rex'.slice(-3) return?
4. What is the difference between replace() and replaceAll() in JavaScript?
5. What will 'A-B-C-D'.split('-') return?
Hands-on tasks in the game
- Click in order
Arrange a call that checks whether dnaSequence contains the fragment 'ACGT':
- Horizontal ordering
Arrange the elements of calling padStart() to pad an ID with zeros: