Strings & Template Literals
slice, includes, replace, split, powerful template literals with ${}, and the concept of string immutability.
Creating Strings
In JavaScript, you can create strings using three types of quotes. Each has its use case, but backtick strings (template literals) are the most powerful and flexible — use them by default in modern JS.
let name1 = 'Alice'; // single quotes let name2 = "Bob"; // double quotes let greeting = `Hello!`; // backtick (template literal) // Strings with special characters let msg1 = "She said \"hello\""; // escaped double quotes let msg2 = 'It\'s great!'; // escaped single quote let msg3 = `No escaping needed for "quotes" or 'apostrophes'`; // backtick wins! console.log(msg1); // She said "hello" console.log(msg2); // It's great! console.log(msg3); // No escaping needed for "quotes" or 'apostrophes'
${}, and no need to escape common quotes. Make them your default choice in all modern JavaScript.String Length
Every string has a .length property that tells you how many characters it contains — including spaces, punctuation, and symbols.
let str = "Hello, World!"; console.log(str.length); // 13 console.log("JavaScript".length); // 10 console.log("".length); // 0 — empty string console.log(" ".length); // 2 — spaces count! // Real-world: validate minimum input length let username = "js_dev"; if (username.length < 3) { console.log("Username too short!"); } else { console.log(`Username OK — ${username.length} characters`); }
str.length, NOT str.length(). Adding parentheses will throw a TypeError because .length is a property (a value), not a callable function. This is a common beginner mistake.Accessing Characters (Indexing)
Strings are zero-indexed — the first character is at position 0, not 1. You can access individual characters using bracket notation or string methods.
let lang = "JavaScript"; // J a v a S c r i p t // 0 1 2 3 4 5 6 7 8 9 // Bracket notation (most common) console.log(lang[0]); // "J" — first character console.log(lang[4]); // "S" console.log(lang[9]); // "t" — last character // Get the last character dynamically console.log(lang[lang.length - 1]); // "t" // .charAt(index) — same as bracket notation console.log(lang.charAt(0)); // "J" console.log(lang.charAt(4)); // "S" // .at(index) — ES2022: supports NEGATIVE indexes! console.log(lang.at(-1)); // "t" — last character console.log(lang.at(-6)); // "S" — 6th from end // Out of bounds returns undefined (not an error) console.log(lang[99]); // undefined
Essential String Methods
JavaScript strings have 40+ built-in methods. Here are the ones you'll reach for every day. Call them with dot notation: string.method().
.toUpperCase() / .toLowerCase()
let city = "karachi"; console.log(city.toUpperCase()); // "KARACHI" console.log("LONDON".toLowerCase()); // "london" // Real-world: case-insensitive comparison let input = "JavaScript"; console.log(input.toLowerCase() === "javascript"); // true
.trim() / .trimStart() / .trimEnd()
let email = " user@example.com "; console.log(email.trim()); // "user@example.com" — removes both ends console.log(email.trimStart()); // "user@example.com " — left only console.log(email.trimEnd()); // " user@example.com" — right only
.includes(searchStr)
let bio = "I love JavaScript"; console.log(bio.includes("JavaScript")); // true console.log(bio.includes("Python")); // false console.log(bio.includes("javascript")); // false (case-sensitive!)
.indexOf(str) / .lastIndexOf(str)
let sentence = "The cat sat on the mat"; console.log(sentence.indexOf("at")); // 5 — first occurrence console.log(sentence.lastIndexOf("at")); // 20 — last occurrence console.log(sentence.indexOf("dog")); // -1 — not found
.startsWith() / .endsWith()
let filename = "report.pdf"; console.log(filename.endsWith(".pdf")); // true console.log(filename.startsWith("rep")); // true console.log(filename.endsWith(".csv")); // false
.slice(start, end)
let text = "JavaScript"; // J a v a S c r i p t // 0 1 2 3 4 5 6 7 8 9 console.log(text.slice(0, 4)); // "Java" — index 0,1,2,3 (4 excluded) console.log(text.slice(4)); // "Script" — from index 4 to end console.log(text.slice(-6)); // "Script" — negative = count from end console.log(text.slice(0, -6)); // "Java" — all except last 6
.replace(old, new) / .replaceAll(old, new)
let msg = "I love cats. Cats are great!"; console.log(msg.replace("cats", "dogs")); // "I love dogs. Cats are great!" — first only! console.log(msg.replaceAll("ats", "ogs")); // "I love cogs. Cogs are great!" — all occurrences
.split(separator)
let csv = "apple,banana,cherry"; let fruits = csv.split(","); console.log(fruits); // ["apple", "banana", "cherry"] // Split into individual characters console.log("hello".split("")); // ["h","e","l","l","o"] // Split by space let words = "Hello World JS".split(" "); console.log(words); // ["Hello", "World", "JS"]
.repeat(n) / .padStart() / .padEnd()
// .repeat(n) — repeat string n times console.log("Ha".repeat(3)); // "HaHaHa" console.log("=".repeat(20)); // "====================" // .padStart(length, char) — pad from the left console.log("5".padStart(3, "0")); // "005" — great for IDs! console.log("7".padStart(5, "0")); // "00007" // .padEnd(length, char) — pad from the right console.log("Hi".padEnd(10, ".")); // "Hi........" console.log("Name".padEnd(10, " ")); // "Name " (space padding)
Template Literals (Backticks)
Template literals are JavaScript's supercharged strings. They use backtick characters (`) and let you embed any expression directly inside using ${expression}. They also support multi-line strings natively — no more \n hacks.
const name = "Aisha"; const age = 22; const city = "Karachi"; // Basic string interpolation — embed variables with ${} console.log(`Hello, my name is ${name}!`); console.log(`I am ${age} years old and live in ${city}.`); console.log(`Next year I'll be ${age + 1}.`); // expressions work too! // Embed complex expressions const price = 9.99; const qty = 3; console.log(`Total: $${(price * qty).toFixed(2)}`); // Total: $29.97 // Multi-line string — no \n needed! const poem = `Roses are red, Violets are blue, JavaScript is awesome, And so are you!`; console.log(poem); // Call functions inside template literals const upper = str => str.toUpperCase(); console.log(`Welcome, ${upper(name)}!`); // "Welcome, AISHA!"
${} you can put any valid JavaScript expression: variables, arithmetic, function calls, ternaries, and more.String Immutability
JavaScript strings are immutable — once created, you cannot change individual characters. Trying to do so silently fails (no error, no change). Instead, you must always create a new string.
let word = "hello"; word[0] = "H"; // silently fails — no error! console.log(word); // still "hello" — nothing changed // Instead, create a new string: word = "H" + word.slice(1); console.log(word); // "Hello" — new string created // All methods return NEW strings — original is untouched let original = "JavaScript"; let upper = original.toUpperCase(); console.log(original); // "JavaScript" — unchanged! console.log(upper); // "JAVASCRIPT" — new string
str = str.toUpperCase(). If you just call str.toUpperCase() without assigning, the result is lost and str stays unchanged. This is a very common mistake!Method Chaining
Because each string method returns a new string, you can chain multiple methods in a single expression. This is a powerful pattern for cleaning and transforming data.
// Chain methods left to right — each operates on the result of the previous const userInput = " Hello, World! "; const cleaned = userInput.trim().toLowerCase().replace("hello", "hi"); console.log(cleaned); // "hi, world!" // Real-world: format a URL slug from a blog title const title = " My Awesome Blog Post! "; const slug = title .trim() // remove spaces: "My Awesome Blog Post!" .toLowerCase() // lowercase: "my awesome blog post!" .replace(/\s+/g, "-") // spaces → dashes: "my-awesome-blog-post!" .replace(/[^a-z0-9-]/g, ""); // remove non-alphanumeric: "my-awesome-blog-post" console.log(slug); // "my-awesome-blog-post"
Regular Expressions — Quick Intro
String methods like .replace() and .test() can work with regular expressions (regex) — powerful pattern matchers that can search, validate, and transform text with incredible precision.
// Basic regex syntax: /pattern/flags const email = "user@example.com"; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; console.log(emailRegex.test(email)); // true — valid email format console.log(emailRegex.test("not-valid")); // false // replace with regex — the 'g' flag means replace ALL occurrences const text = "foo bar baz bar foo"; console.log(text.replace(/bar/g, "---")); // "foo --- baz --- foo" // Match digits const phone = "Call 0300-1234567 now"; const digits = phone.match(/\d+/g); console.log(digits); // ["0300", "1234567"]
.replace(), .match(), and .test().Summary
.at(-1) for the last character with negative indexing..toUpperCase(), .trim(), .includes(), .slice(), .replace(), .split(), .padStart() — your daily toolkit.${}, write multi-line strings naturally. The modern, preferred way to build dynamic strings."Hello".length in JavaScript?`Hello ${name}!` syntax in JavaScript use?"JavaScript".slice(4)?formatName that:1. Takes a raw input string like
" john doe "2. Trims whitespace
3. Splits into first and last name
4. Capitalizes the first letter of each
5. Returns a formatted string:
"John Doe"Also create a function called
makeSlug(title) that converts "My Blog Post Title!" to "my-blog-post-title".Test both functions with at least 3 different inputs.
💡 Show hints
- Use
.trim()then.split(" ")to get name parts - Filter out empty strings from split with
.filter(Boolean) - Capitalize:
word[0].toUpperCase() + word.slice(1) - Use
.map()to capitalize each word, then.join(" ") - For slug:
.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "")
// ── Name Formatter ─────────────────────────────── function formatName(rawInput) { return rawInput .trim() // remove leading/trailing spaces .split(/\s+/) // split on one or more spaces .filter(Boolean) // remove empty strings .map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()) .join(" "); // rejoin with single space } // ── URL Slug Generator ─────────────────────────── function makeSlug(title) { return title .trim() // remove edge spaces .toLowerCase() // all lowercase .replace(/\s+/g, "-") // spaces → dashes .replace(/[^a-z0-9-]/g, ""); // remove special chars } // ── Test it out ────────────────────────────────── console.log(formatName(" john doe ")); // "John Doe" console.log(formatName("AISHA khan")); // "Aisha Khan" console.log(formatName(" ali RAZA ")); // "Ali Raza" console.log(makeSlug("My Blog Post Title!")); // "my-blog-post-title" console.log(makeSlug(" 10 Awesome JS Tips ")); // "10-awesome-js-tips" console.log(makeSlug("What's new in ES2024?")); // "whats-new-in-es2024"