Strings and template literals
A string is a sequence of characters: names, messages, addresses, passwords. Almost every application handles text, so mastering strings is essential. You can write them with single quotes, double quotes or backticks. Single and double quotes are equivalent; choose one and be consistent. Backticks have superpowers that you will see right away.
Template literals
A template literal is written between backticks and lets you insert any expression with the ${...} syntax. It is much more comfortable and readable than joining pieces with the + sign. It also allows several lines without special characters. Inside the braces you can put variables, calculations or function calls.
const user = 'Marta';
const items = 3;
const price = 4.5;
// Old way
console.log('Hi ' + user + ', you have ' + items + ' items.');
// Template literal
console.log(`Hi ${user}, you have ${items} items.`);
console.log(`Total: ${(items * price).toFixed(2)} EUR`);
const message = `Line one
Line two`;
console.log(message);String properties and methods
Strings have the length property (how many characters) and many methods. Remember that strings are immutable: no method changes the original, all of them return a new string. To access a character use brackets with an index that starts at 0. With at(-1) you get the last character. The methods you will use most are toUpperCase, toLowerCase, trim (removes spaces from the ends), includes, startsWith, slice, split, replaceAll and padStart.
const text = ' Learn JavaScript Today ';
const clean = text.trim();
console.log(clean.length); // 22
console.log(clean.toUpperCase()); // LEARN JAVASCRIPT TODAY
console.log(clean[0]); // L
console.log(clean.at(-1)); // y
console.log(clean.includes('Script')); // true
console.log(clean.slice(0, 5)); // Learn
console.log(clean.split(' ')); // [ 'Learn', 'JavaScript', 'Today' ]
console.log(clean.replaceAll('a', '4')); // Le4rn J4v4Script Tod4y
console.log('7'.padStart(3, '0')); // 007
clean.toUpperCase();
console.log(clean); // unchanged: Learn JavaScript TodaySpecial characters and common mistakes
To include quotes inside a text of the same kind you must escape them with a backslash, for example 'It\'s'; you can also alternate the type of quote. \n is a line break and \t is a tab. A very typical mistake is forgetting that methods return a new value: writing text.toUpperCase() without saving the result changes nothing. Another is mixing up slice indexes: slice(0, 5) includes position 0 and excludes position 5.
Complete example: a user card
Let us put together what you learned with a realistic example. You have the name and email of a person written carelessly, with spaces and mixed capitals. First you clean with trim, normalize the email with toLowerCase, extract the domain with split and an index, and finally you build a message with a template literal that includes several expressions. Notice that each step returns a new string that feeds the next one; chaining methods is very common and reads from left to right like a recipe. When a text comes from a form, always apply trim before validating it.
const rawName = ' mARIA gOMEZ ';
const rawEmail = ' Maria.Gomez@Example.COM ';
const name = rawName.trim().toLowerCase();
const email = rawEmail.trim().toLowerCase();
const domain = email.split('@')[1];
const initials = name.split(' ').map((w) => w[0].toUpperCase()).join('');
console.log(`User: ${name} <${email}>`);
console.log(`Domain: ${domain}, initials: ${initials}`);
// User: maria gomez <maria.gomez@example.com>
// Domain: example.com, initials: MGPractice these methods with real texts: a title, a sentence, an email address. The more you use them, the faster you will remember their names, and the MDN documentation will help you discover other very useful ones, such as startsWith, endsWith or repeat.
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen