# String Methods & Template Literals

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-string-methods
Last updated: 2026-11-28

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

| Task | Method | Example result |
| --- | --- | --- |
| Contains | `'swiggy'.includes('wig')` | `true` |
| Prefix / suffix | `str.startsWith('ORD-')`, `str.endsWith('.pdf')` | `true` / `false` |
| Position | `indexOf`, `lastIndexOf` | index or `-1` |
| Substring | `slice(start, end)` | negative indexes count from the end |
| Single char | `at(-1)` (ES2022) | last character |
| Clean up | `trim`, `trimStart`, `trimEnd` | whitespace removed |
| Case | `toLowerCase`, `toUpperCase` | new string |
| Replace | `replace` (first match), `replaceAll` (ES2021) | new string |
| Pad | `padStart(10, '0')` | zero-padded ID |
| Split / join | `split(',')`, `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:

- Interpolation: `${expression}` evaluates any expression, including function calls and ternaries, and converts the result with `String()`.
- Multi-line text without `\n` escapes. Indentation inside the literal becomes part of the string, which can surprise you.
- Nesting: a template literal can appear inside another one's `${}`.

### Tagged templates

A tag is a function placed before the literal: \`` sql`SELECT \* 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:

- Escaping or parameterising values, as in libraries such as `postgres` (porsager) and `sql-template-tag`, which turn the values into query parameters and so prevent SQL injection.
- Styled-components and Emotion's `css` tag for CSS-in-JS.
- `String.raw`, a built-in tag that ignores escape sequences, useful for Windows paths and regex strings.

### 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('&', '&amp;')
    .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

- Strings are immutable; always use the returned value
- Prefer slice over substring and the deprecated substr
- replace changes only the first match; use replaceAll or a /g regex
- A tag function gets (strings, ...values) and can return any type
- length counts UTF-16 code units, not visible characters

## Common follow-up questions

- How would you reverse a string that contains emoji correctly?
- How do tagged templates help prevent SQL injection?
- What is the difference between slice, substring and substr?
- How would you check if a string is a palindrome ignoring case and spaces?

## Interview tips

- Mention immutability early; it explains why name.trim() alone does nothing
- If asked about tagged templates, name a real library use such as styled-components or SQL tags
- Bring up the Unicode length issue; it signals real-world experience

## Concepts covered

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

Previous: [Operators & Short-Circuit Evaluation](https://www.internhack.in/learn/interview/javascript-interview/js-operators-short-circuit) · Next: [Array Methods (map, filter, reduce)](https://www.internhack.in/learn/interview/javascript-interview/js-array-methods) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread)
- [Error Handling (try/catch/finally)](https://www.internhack.in/learn/interview/javascript-interview/js-error-handling)
- [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators)
- [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions)
- [Template Literals & String Interpolation](https://www.internhack.in/learn/interview/javascript-interview/js-template-literals)
- [null vs undefined](https://www.internhack.in/learn/interview/javascript-interview/js-null-undefined)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
