String Methods & Template Literals

Difficulty: Beginner

Question

What are the most important string methods in JavaScript, and how do template literals and tagged templates work?

Answer

Strings in JavaScript are immutable sequences of UTF-16 code units, so every string method returns a new string instead of changing the original. The methods you use daily fall into a few groups: searching (includes, startsWith, indexOf), extracting (slice, at), transforming (trim, toLowerCase, replaceAll, padStart) and splitting (split). Template literals, written with backticks, add interpolation with ${}, multi-line strings and tagged templates, where a function processes the literal.

The methods worth knowing cold

TaskMethodExample result
Contains'swiggy'.includes('wig')true
Prefix / suffixstr.startsWith('ORD-'), str.endsWith('.pdf')true / false
PositionindexOf, lastIndexOfindex or -1
Substringslice(start, end)negative indexes count from the end
Single charat(-1) (ES2022)last character
Clean uptrim, trimStart, trimEndwhitespace removed
CasetoLowerCase, toUpperCasenew string
Replacereplace (first match), replaceAll (ES2021)new string
PadpadStart(10, '0')zero-padded ID
Split / joinsplit(','), arr.join(', ')array / string
Repeat'-'.repeat(20)separator line

Prefer slice over substring (which swaps arguments and treats negatives as 0) and over the deprecated substr. replace with a string only replaces the first occurrence; use replaceAll or a regex with the g flag for all of them.

Immutability and why it matters

str[0] = 'X' silently does nothing (and throws in strict mode for some cases). Calling name.trim() without assigning the result is a very common bug. Building a long string with += in a loop is fine in modern engines, which use rope structures internally, but array.join('') is still the clearest way to assemble many pieces.

Template literals

Backtick strings support:

Tagged templates

A tag is a function placed before the literal: ` sqlSELECT * FROM users WHERE id = ${id} `. The function receives an array of the static string parts and then each interpolated value as separate arguments. It can return anything, not just a string. Real uses:

Unicode gotchas

length counts UTF-16 code units, not visible characters. Many emoji and some Devanagari conjuncts take two or more units, so '\u{1F600}'.length is 2. [...str] splits by code point, and Intl.Segmenter splits by user-perceived characters (grapheme clusters) when you need exact counts, for example to enforce a 160-character SMS limit correctly.

Chaining string methods, character by character. Build your own chain under Tweak. The original string never changes.
  1. Strings are immutable: Every method returns a new string.
  2. trim: Removes whitespace at both ends only.
  3. toLowerCase / toUpperCase: Map every character.
  4. replaceAll: Replaces every occurrence; replace only the first.

Code examples

Everyday string methods

const raw = '  ORD-2026-0042  ';
const id = raw.trim();

console.log(id.startsWith('ORD-'));        // true
console.log(id.slice(-4));                 // 0042
console.log(id.at(0));                     // O
console.log(id.split('-'));                // [ 'ORD', '2026', '0042' ]
console.log('a-b-c'.replace('-', '+'));    // a+b-c
console.log('a-b-c'.replaceAll('-', '+')); // a+b+c
console.log(String(7).padStart(4, '0'));   // 0007
console.log(raw.length, id.length);        // 17 13 (original unchanged)

Every method returns a new string; raw still has its spaces. replace only touches the first match unless you use replaceAll or a global regex.

Template literals

const user = { name: 'Priya', plan: 'Pro' };
const amountPaise = 49900;

const msg = `Hi ${user.name},
Your ${user.plan} plan renews for Rs ${(amountPaise / 100).toFixed(2)}.
Status: ${amountPaise > 0 ? 'Payable' : 'Free'}`;

console.log(msg);

Any expression works inside ${}, and line breaks in the literal are preserved in the output.

Writing a tagged template

function escapeHtml(strings, ...values) {
  const esc = (v) => String(v)
    .replaceAll('&', '&')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;');
  // strings has one more element than values
  return strings.reduce(
    (out, str, i) => out + str + (i < values.length ? esc(values[i]) : ''),
    ''
  );
}

const comment = '<script>alert(1)</script>';
console.log(escapeHtml`<p>${comment}</p>`);
console.log(String.raw`C:\new\table`);

The tag receives the static parts and the interpolated values separately, so it can sanitise only the values. String.raw keeps backslashes literally.

Key points

Common follow-up questions

Interview tips

Concepts covered

String Methods, Template Literals, Tagged Templates, String Immutability, Unicode

More JavaScript Interview questions