CodeMIRAI
0 XP

Strings and template literals

2 min read 8 runnable examples Quiz included

Three kinds of quotes

JavaScript
const single = 'Hello';
const double = "World";
const name = "Asha";
const template = `Hi ${name}, 2 + 2 = ${2 + 2}`;   // backticks
console.log(single, double);
console.log(template);

Template literals (backticks) can insert any expression with ${...} and can span multiple lines:

JavaScript
const item = "Keyboard", price = 89.99, qty = 2;
console.log(`Receipt
  ${item} x ${qty}
  Total: ${(price * qty).toFixed(2)}`);

Length and characters

JavaScript
const word = "JavaScript";
console.log(word.length);
console.log(word[0], word[word.length - 1], word.at(-1));

Strings are immutable: methods return new strings and never change the original.

Changing case and trimming

JavaScript
const raw = "   Hello World   ";
console.log(raw.toUpperCase());
console.log(raw.toLowerCase());
console.log(`[${raw.trim()}]`);
console.log(`[${raw.trimStart()}]`);

Searching

JavaScript
const s = "Learning JavaScript is fun";
console.log(s.includes("Java"));
console.log(s.startsWith("Learn"), s.endsWith("fun"));
console.log(s.indexOf("Script"));      // position, or -1
console.log(s.indexOf("Python"));

Slicing

JavaScript
const s = "JavaScript";
console.log(s.slice(0, 4));     // from 0 up to (not including) 4
console.log(s.slice(4));        // from 4 to the end
console.log(s.slice(-6));       // the last 6 characters

Splitting, joining and replacing

JavaScript
const csv = "Asha,21,Mumbai";
const parts = csv.split(",");
console.log(parts);
console.log(parts.join(" | "));

const text = "cats are great, cats are fun";
console.log(text.replace("cats", "dogs"));       // first only
console.log(text.replaceAll("cats", "dogs"));    // every one

Padding and repeating

JavaScript
console.log("7".padStart(3, "0"));
console.log("Total".padEnd(10, ".") + "42");
console.log("=".repeat(20));
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.