We use cookies to enhance your experience on the site
CodeWorlds

Template Literals and String Methods

In Jurassic Park, every report, every status message, every alert must be formatted correctly. Template literals and string methods are your tools for working with text - from simple interpolation to complex transformations.

Template Literals

Template literals use backticks (`) and enable multi-line strings and embedded expressions:

1const dinoName = 'Rex';
2const health = 95;
3const zone = 'A';
4
5// Old way with concatenation
6const oldReport = 'Dinosaur: ' + dinoName + ', Health: ' + health + '%, Zone: ' + zone;
7
8// Template literal - cleaner!
9const report = `Dinosaur: ${dinoName}, Health: ${health}%, Zone: ${zone}`;
10
11// Any expression can go in ${}
12const status = `Status: ${health > 80 ? 'Excellent' : 'Needs attention'}`;
13
14// Multi-line strings
15const multiLine = `
16=== PARK REPORT ===
17Dinosaur: ${dinoName}
18Health: ${health}%
19Zone: ${zone}
20Status: ${health > 80 ? 'OK' : 'CRITICAL'}
21`;

Expressions in Template Literals

1const dinos = [
2  { name: 'Rex', weight: 8000 },
3  { name: 'Blue', weight: 15 }
4];
5
6// Function calls in template literals
7const list = `Dinosaurs: ${dinos.map(d => d.name).join(', ')}`;
8// "Dinosaurs: Rex, Blue"
9
10// Math in template literals
11const total = `Total weight: ${dinos.reduce((s, d) => s + d.weight, 0)}kg`;
12// "Total weight: 8015kg"
13
14// Nested template literals
15const table = dinos
16  .map(d => `  ${d.name.padEnd(10)} | ${d.weight.toString().padStart(6)}kg`)
17  .join('\n');

Tagged Templates

Tagged templates let you preprocess a template literal with a function:

1function highlight(strings, ...values) {
2  return strings.reduce((result, str, i) => {
3    const value = values[i - 1];
4    return result + (value !== undefined ? `[[${value}]]` : '') + str;
5  });
6}
7
8const name = 'Rex';
9const health = 95;
10const tagged = highlight`Dinosaur ${name} has health ${health}%`;
11console.log(tagged); // "Dinosaur [[Rex]] has health [[95]]%"
12
13// Practical: SQL query builder
14function sql(strings, ...values) {
15  const query = strings.join('?');
16  return { query, params: values };
17}
18
19const zone = 'A';
20const minHealth = 80;
21const query = sql`SELECT * FROM dinos WHERE zone = ${zone} AND health > ${minHealth}`;
22// { query: "SELECT * FROM dinos WHERE zone = ? AND health > ?", params: ['A', 80] }

String Methods

Searching

1const description = 'T-Rex is a carnivore living in Zone A of Jurassic Park';
2
3// indexOf / lastIndexOf
4console.log(description.indexOf('Rex'));     // 2
5console.log(description.indexOf('raptor'));  // -1 (not found)
6
7// includes
8console.log(description.includes('carnivore')); // true
9console.log(description.includes('Zone B'));    // false
10
11// startsWith / endsWith
12console.log(description.startsWith('T-Rex'));       // true
13console.log(description.endsWith('Jurassic Park')); // true
14console.log(description.startsWith('Rex', 2));       // true (from position 2)
15
16// match / matchAll
17const text = 'Zone A has 3 dinos, Zone B has 5 dinos';
18const zones = text.match(/Zone [A-Z]/g);
19console.log(zones); // ['Zone A', 'Zone B']

Extracting

1const code = 'DINO-001-T-REX-ZONE-A';
2
3// slice(start, end)
4console.log(code.slice(5, 8));   // "001"
5console.log(code.slice(-6));     // "ZONE-A"
6
7// split
8const parts = code.split('-');
9// ['DINO', '001', 'T', 'REX', 'ZONE', 'A']
10
11// Destructuring after split
12const [prefix, id, ...rest] = code.split('-');
13console.log(prefix); // "DINO"
14console.log(id);     // "001"

Modifying

1const raw = '  Rex is a T-Rex  ';
2
3// trim family
4console.log(raw.trim());       // "Rex is a T-Rex"
5console.log(raw.trimStart());  // "Rex is a T-Rex  "
6console.log(raw.trimEnd());    // "  Rex is a T-Rex"
7
8// Case
9console.log('rex'.toUpperCase()); // "REX"
10console.log('T-REX'.toLowerCase()); // "t-rex"
11
12// replace / replaceAll
13const msg = 'Zone A dino Zone A escaped Zone A fences';
14console.log(msg.replace('Zone A', 'Zone B'));     // only first
15console.log(msg.replaceAll('Zone A', 'Zone B'));  // all occurrences
16
17// padStart / padEnd - padding
18const num = 42;
19console.log(num.toString().padStart(6, '0')); // "000042"
20console.log('Rex'.padEnd(10, '.'));           // "Rex......."
21
22// repeat
23console.log('-'.repeat(30)); // "------------------------------"

Method Chaining

1function formatReport(rawInput) {
2  return rawInput
3    .trim()
4    .toLowerCase()
5    .replace(/s+/g, '-')     // spaces to hyphens
6    .replace(/[^a-z0-9-]/g, '') // remove non-alphanumeric
7    .slice(0, 50);            // max 50 chars
8}
9
10console.log(formatReport('  T-Rex Escape!! Zone A  '));
11// "t-rex-escape-zone-a"

"Template literals and string methods are like the park's communication system" - says Dr. Rex. "Template literals craft the perfect message, string methods format and process the text. Together they turn raw data into clear, professional reports!"

Go to CodeWorlds