//
Strings are one of the most frequently used data types. JavaScript provides a rich set of built-in methods for searching, extracting, transforming, and formatting strings.
1const single = 'Hello';2const double = "Hello";3const backtick = `Hello`;45// Template literals - interpolation and multi-line6const name = "Alice";7const greeting = `Hello, ${name}!`; // "Hello, Alice!"8const calc = `2 + 2 = ${2 + 2}`; // "2 + 2 = 4"9const multiline = `Line 110Line 211Line 3`;
Use Template Literals
Prefer backtick template literals over + concatenation. They're cleaner, support expressions, and handle multi-line strings natively.
1const str = "JavaScript";23console.log(str.length); // 104console.log(str[0]); // "J"5console.log(str[4]); // "S"6console.log(str.at(-1)); // "t" (negative indexing with .at())7console.log(str[100]); // undefined89// Strings are IMMUTABLE10str[0] = "j"; // No error, but no effect11console.log(str); // "JavaScript" (unchanged)
| Method | Returns | Description |
|---|---|---|
indexOf(str) | Number | First index, or -1 |
lastIndexOf(str) | Number | Last index, or -1 |
includes(str) | Boolean | Contains substring? |
startsWith(str) | Boolean | Starts with? |
endsWith(str) | Boolean | Ends with? |
search(regex) | Number | First regex match index |
1const text = "JavaScript is awesome. JavaScript is everywhere.";23console.log(text.indexOf("JavaScript")); // 04console.log(text.lastIndexOf("JavaScript")); // 235console.log(text.includes("awesome")); // true6console.log(text.startsWith("Java")); // true7console.log(text.endsWith("everywhere.")); // true89// Case-insensitive search10console.log(text.toLowerCase().includes("javascript")); // true
1const str = "Hello, World!";23// slice(start, end) - most versatile4console.log(str.slice(0, 5)); // "Hello"5console.log(str.slice(7)); // "World!"6console.log(str.slice(-6)); // "orld!"7console.log(str.slice(-6, -1)); // "orld"89// substring(start, end) - no negative indices10console.log(str.substring(0, 5)); // "Hello"1112// charAt(index)13console.log(str.charAt(0)); // "H"14console.log(str.charAt(100)); // "" (empty string)
Use slice()
Prefer slice() over substring() - it supports negative indices and has more predictable behavior with swapped arguments.
1const str = " Hello, World! ";23// Case4console.log(str.toUpperCase()); // " HELLO, WORLD! "5console.log(str.toLowerCase()); // " hello, world! "67// Trimming whitespace8console.log(str.trim()); // "Hello, World!"9console.log(str.trimStart()); // "Hello, World! "10console.log(str.trimEnd()); // " Hello, World!"1112// Replacing13const msg = "I love cats. cats are great.";14console.log(msg.replace("cats", "dogs")); // "I love dogs. cats are great."15console.log(msg.replaceAll("cats", "dogs")); // "I love dogs. dogs are great."1617// Padding18console.log("5".padStart(3, "0")); // "005"19console.log("5".padEnd(3, "0")); // "500"20console.log("42".padStart(5)); // " 42"2122// Repeating23console.log("ha".repeat(3)); // "hahaha"24console.log("-".repeat(20)); // "--------------------"
1// Split string → array2const csv = "apple,banana,cherry";3const fruits = csv.split(",");4console.log(fruits); // ["apple", "banana", "cherry"]56const words = "Hello World".split(" ");7console.log(words); // ["Hello", "World"]89const chars = "Hello".split("");10console.log(chars); // ["H", "e", "l", "l", "o"]1112// Join array → string13console.log(fruits.join(" | ")); // "apple | banana | cherry"14console.log(fruits.join("")); // "applebananacherry"
1// Strings compare lexicographically (by Unicode code points)2console.log("a" < "b"); // true3console.log("A" < "a"); // true (uppercase comes first)4console.log("10" < "9"); // true! ("1" < "9" by first char)56// Case-insensitive comparison7const a = "Hello";8const b = "hello";9console.log(a.toLowerCase() === b.toLowerCase()); // true1011// localeCompare for proper sorting12console.log("café".localeCompare("cafe")); // 1 (café comes after)
String Number Comparison
"10" < "9" is true because strings compare character by character. Convert to numbers first if comparing numeric strings.
1// Reverse a string2const reversed = "Hello".split("").reverse().join("");3console.log(reversed); // "olleH"45// Capitalize first letter6function capitalize(str) {7return str.charAt(0).toUpperCase() + str.slice(1);8}9console.log(capitalize("hello")); // "Hello"1011// Count occurrences12function countChar(str, char) {13return str.split(char).length - 1;14}15console.log(countChar("banana", "a")); // 31617// Truncate with ellipsis18function truncate(str, maxLength) {19return str.length > maxLength20? str.slice(0, maxLength - 3) + "..."21: str;22}23console.log(truncate("This is a long sentence", 15)); // "This is a lo..."
1function createSlug(title) {2return title3.toLowerCase()4.trim()5.replaceAll(" ", "-")6.replace(/[^a-z0-9-]/g, "") // remove special chars7.replace(/-+/g, "-") // collapse multiple hyphens8.replace(/^-|-$/g, ""); // trim leading/trailing hyphens9}1011console.log(createSlug("Hello World!"));12// "hello-world"1314console.log(createSlug(" JavaScript: The Good Parts "));15// "javascript-the-good-parts"1617console.log(createSlug("10 Tips & Tricks for React.js"));18// "10-tips--tricks-for-reactjs"
Next up: Numbers & Math - learn about the Math object, number formatting, parsing, and precision handling.