Difficulty: Beginner
What are the most important string methods in JavaScript? Explain template literals and tagged templates.
Strings in JavaScript are immutable - every string method returns a new string rather than modifying the original. Key methods include slice(), substring(), includes(), startsWith(), endsWith(), indexOf(), replace(), replaceAll(), split(), trim(), padStart(), padEnd(), and repeat().
Template literals (backtick strings) allow embedded expressions with ${}, multi-line strings without escape characters, and tagged template functions. Tagged templates let you parse template literals with a custom function, which is useful for sanitization, internationalization, and DSLs like styled-components.
Modern JavaScript also provides at() for negative indexing and matchAll() for regex iteration.
const str = ' Hello, JavaScript World! ';
// Searching
console.log(str.includes('JavaScript')); // true
console.log(str.indexOf('World')); // 19
console.log(str.startsWith(' Hello')); // true
// Extracting
console.log(str.trim()); // 'Hello, JavaScript World!'
console.log(str.trim().slice(7, 17)); // 'JavaScript'
console.log(str.trim().split(', ')); // ['Hello', 'JavaScript World!']
// Transforming
console.log('hello'.toUpperCase()); // 'HELLO'
console.log('abc'.repeat(3)); // 'abcabcabc'
console.log('5'.padStart(3, '0')); // '005'
console.log('hello'.replace('l', 'L')); // 'heLlo' (first only)
console.log('hello'.replaceAll('l', 'L')); // 'heLLo'
All methods return new strings. replace() only replaces the first match; use replaceAll() or a regex with /g for all matches.
const name = 'Alice';
const age = 25;
// Expression interpolation
console.log(`${name} is ${age} years old`);
// Multi-line
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>`;
console.log(html.trim());
// Expressions inside ${}
console.log(`Total: ${(49.99 * 1.18).toFixed(2)}`);
console.log(`Status: ${age >= 18 ? 'Adult' : 'Minor'}`);
Template literals support any JavaScript expression inside ${}. They preserve whitespace and newlines.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] !== undefined ? `${values[i]}` : '';
return result + str + value;
}, '');
}
const name = 'Alice';
const role = 'developer';
console.log(highlight`${name} is a ${role}`);
// Practical: SQL-safe template
function sql(strings, ...values) {
const escaped = values.map(v =>
typeof v === 'string' ? v.replace(/'/g, "''") : v
);
return strings.reduce((q, str, i) =>
q + str + (escaped[i] !== undefined ? `'${escaped[i]}'` : ''), '');
}
console.log(sql`SELECT * FROM users WHERE name = ${"O'Brien"}`);
Tagged templates receive split string parts and interpolated values separately, letting you process them before combining. This is the basis for styled-components and GraphQL gql tags.
String Methods, Template Literals, Tagged Templates, String Immutability, RegExp