Difficulty: Beginner
What are the most important string methods in JavaScript, and how do template literals and tagged templates work?
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.
| 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.
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.
Backtick strings support:
${expression} evaluates any expression, including function calls and ternaries, and converts the result with String().\n escapes. Indentation inside the literal becomes part of the string, which can surprise you.${}.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:
postgres (porsager) and sql-template-tag, which turn the values into query parameters and so prevent SQL injection.css tag for CSS-in-JS.String.raw, a built-in tag that ignores escape sequences, useful for Windows paths and regex strings.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.
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.
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.
function escapeHtml(strings, ...values) {
const esc = (v) => String(v)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>');
// 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.
String Methods, Template Literals, Tagged Templates, String Immutability, Unicode