Skip to content
elephantoo

Strings & template literals

Lesson 4 of 34 14 min read

Quotes, escapes, template literals and the string methods you will use every day.


Text is everywhere: names, messages, URLs, HTML, CSV files. In JavaScript, text is the string type. This lesson covers how to write strings, build them with template literals, and use the built-in methods you'll reach for every day.

Three ways to write a string#

JavaScript
const single = 'Hello';
const double = "Hello";
const backtick = `Hello`;
console.log(single === double && double === backtick); // true

Single and double quotes are identical — pick one and let a formatter enforce it. Backticks create template literals, which have superpowers.

Escape sequences

Use a backslash to include special characters:

JavaScript
console.log("She said \"hi\"");  // She said "hi"
console.log('It\'s here');       // It's here
console.log("Line 1\nLine 2");   // \n is a newline
console.log("Tab\tseparated");   // \t is a tab
console.log("Backslash: \\");    // Backslash: \

Or avoid escaping by choosing the other quote: "It's here".

Template literals#

Backtick strings can interpolate any expression with ${...} and can span lines:

JavaScript
const name = "Ada";
const done = 7;
const total = 10;

console.log(`${name} has finished ${done} of ${total} lessons.`);
console.log(`Progress: ${Math.round((done / total) * 100)}%`);
console.log(`Status: ${done === total ? "complete 🎉" : "keep going"}`);

const html = `
<article>
  <h2>${name}</h2>
</article>`;
console.log(html.trim());
Output
Ada has finished 7 of 10 lessons.
Progress: 70%
Status: keep going
<article>
  <h2>Ada</h2>
</article>

Compare the old way: name + " has finished " + done + " of " + total + " lessons." — template literals are far easier to read.

Security tip: building HTML with template literals and inserting it with innerHTML is dangerous if any value comes from a user. You'll learn the safe approach in the DOM lesson.

Length, indexes and characters#

JavaScript
const word = "JavaScript";
console.log(word.length);          // 10
console.log(word[0]);              // "J"
console.log(word.at(-1));          // "t" – at() accepts negative indexes
console.log(word[word.length - 1]); // "t" – the older way
console.log(word[50]);             // undefined

Strings are immutable. Methods never change the original; they return a new string:

JavaScript
const original = "hello";
const shout = original.toUpperCase();
console.log(original, shout); // hello HELLO

Everyday string methods#

Changing case and trimming

JavaScript
const raw = "   Ada@Example.COM  ";
const email = raw.trim().toLowerCase();
console.log(email);                 // "ada@example.com"
console.log("  x  ".trimStart());   // "x  "
console.log("  x  ".trimEnd());     // "  x"

Trim and normalise user input before comparing or saving it.

Searching

JavaScript
const sentence = "Learn JavaScript on Elephantoo";
console.log(sentence.includes("Script"));   // true
console.log(sentence.startsWith("Learn"));  // true
console.log(sentence.endsWith("too"));      // true
console.log(sentence.indexOf("a"));        // 2 – first position
console.log(sentence.lastIndexOf("a"));    // 25 – last position
console.log(sentence.indexOf("Python"));   // -1 – not found

Searches are case-sensitive. For case-insensitive checks, lower-case both sides first.

Extracting parts

JavaScript
const lang = "JavaScript";
console.log(lang.slice(0, 4));  // "Java"  – from 0 up to (not including) 4
console.log(lang.slice(4));     // "Script"
console.log(lang.slice(-6));    // "Script" – negative counts from the end
console.log(lang.substring(4, 0)); // "Java" – substring swaps reversed args

Prefer slice — it's consistent with arrays and supports negative indexes.

Splitting and joining

JavaScript
const csv = "html,css,javascript";
const parts = csv.split(",");
console.log(parts);                  // [ 'html', 'css', 'javascript' ]
console.log(parts.join(" · "));      // "html · css · javascript"
console.log("hi".split(""));         // [ 'h', 'i' ]
console.log("one two  three".split(" ")); // [ 'one', 'two', '', 'three' ]

Replacing

JavaScript
const slug = "learn-js-today";
console.log(slug.replace("-", " "));    // "learn js-today" – first only!
console.log(slug.replaceAll("-", " ")); // "learn js today"

Padding and repeating

JavaScript
console.log("7".padStart(3, "0"));   // "007"
console.log("Total".padEnd(10, ".") + "₹499"); // "Total.....₹499"
console.log("ab".repeat(3));         // "ababab"

padStart is perfect for times ("05") and invoice numbers.

Comparing strings#

JavaScript
console.log("apple" === "apple");          // true
console.log("Apple" === "apple");          // false
console.log("a".localeCompare("b"));        // -1  (a sorts before b)
console.log("résumé".localeCompare("resume", "en", { sensitivity: "base" })); // 0 – equal ignoring accents

Converting to and from strings#

JavaScript
console.log(String(42));          // "42"
console.log((3.14159).toFixed(2)); // "3.14" – note: returns a string
console.log(Number("3.14") + 1);   // 4.140000000000001 – floating point again
console.log(`${[1, 2, 3]}`);       // "1,2,3"
console.log(JSON.stringify({ a: 1 })); // '{"a":1}'

Unicode and emoji#

JavaScript strings are UTF-16. Most characters take one "code unit", but emoji and some symbols take two:

JavaScript
const emoji = "🐘";
console.log(emoji.length);       // 2 – surprise!
console.log([...emoji].length);  // 1 – spreading iterates by code point
console.log("héllo".length);     // 5

When counting user-visible characters (e.g. a tweet-length limit), use [...str].length. For full accuracy with combined emoji like 👨‍👩‍👧, use Intl.Segmenter.

A worked example: making a URL slug#

JavaScript
function slugify(title) {
  return title
    .trim()
    .toLowerCase()
    .replaceAll(" ", "-")
    .replaceAll("&", "and");
}

console.log(slugify("  Arrays & Objects  ")); // "arrays-and-objects"
console.log(slugify("DOM Events"));           // "dom-events"

Chaining methods like this works because each one returns a new string. In the Regular expressions lesson you'll write a more robust version.

Common mistakes#

  • Expecting replace to replace everything — use replaceAll.
  • Forgetting strings are immutable: name.toUpperCase(); on its own line does nothing useful; assign the result.
  • Using + with numbers from inputs: "2" + "2" is "22".
  • Using substr — it's deprecated. Use slice.

What's next#

Now that you can build and inspect text, it's time to make decisions with conditionals.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What does "Elephantoo".slice(-3) return?

  2. 2.Given const s = "hello"; s[0] = "J";, what is s afterwards?

  3. 3.Which method replaces **every** occurrence of "-" in a string?

Finished reading?

Mark this lesson complete to track your progress.