Strings and template literals

JavaScript · Essentials · 10 min

Most programs spend a lot of time building, slicing and checking text.

Strings can use single quotes, double quotes or backticks. Backticks create template literals, which allow interpolation with ${expression} and can span multiple lines:

const msg = `Hello ${user.name}, you have ${count + 1} items`;

Strings are immutable: every method returns a new string and leaves the original alone. The ones you'll use constantly:

  • length, str[0], str.at(-1) (negative indexes count from the end)
  • includes, startsWith, endsWith, indexOf
  • slice(start, end) — end is exclusive; negatives count from the end
  • toUpperCase, toLowerCase, trim, trimStart, trimEnd
  • split(separator) to get an array, and array.join(sep) to go back
  • replace (first match) and replaceAll (every match)
  • padStart(len, ch) for things like zero-padding: "7".padStart(3, "0") is "007"
  • repeat(n)

Comparison with < and > compares UTF-16 code units, so "Z" < "a" is true. For human-facing sorting use a.localeCompare(b) or Intl.Collator.

One Unicode gotcha: length counts UTF-16 code units, so an emoji outside the basic plane (like "😀") has length 2. Iterating with for...of or spreading [...str] walks whole code points instead, which is what you usually want for user text.

Escape sequences such as \n (newline) and \t (tab) work in all three quote styles.

Example

const name = "Ada Lovelace";
console.log(`Hi ${name.split(" ")[0]}!`); // Hi Ada!

console.log(name.length);            // 12
console.log(name.slice(0, 3));       // "Ada"
console.log(name.at(-1));            // "e"
console.log(name.includes("Love"));  // true
console.log(name.toUpperCase());     // "ADA LOVELACE"

const csv = " a, b ,c ";
console.log(csv.split(",").map(s => s.trim())); // [ 'a', 'b', 'c' ]
console.log("2-5-2025".replaceAll("-", "/"));   // "2/5/2025"
console.log(String(7).padStart(3, "0"));        // "007"

console.log("😀".length, [..."😀"].length);      // 2 1

Remember

  • Template literals: backticks plus ${expr} for interpolation and multi-line text
  • String methods never modify the original — they return a new string
  • length counts UTF-16 units; use [...str] to count characters users see as one

Watch out for

  • Calling str.replace("a", "b") and expecting every match replaced — use replaceAll.

Check yourself

  1. const s = "hello"; s.toUpperCase(); console.log(s); — what is logged?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Strings and template literals · JavaScript · Topolearn