JavaScript provides a rich suite of built-in methods for manipulating, extracting, transforming, and padding string data. All string methods return new strings without mutating the original primitive.
flowchart TD
Methods["String Methods"] --> Slice["Extraction: slice(), substring(), split()"]
Methods --> Transform["Transformation: toUpperCase(), toLowerCase(), trim(), replace()"]
Methods --> Pad["Padding: padStart(), padEnd(), repeat()"]
| Method | Signature | Returns | Description |
|---|---|---|---|
slice(start, end) |
str.slice(0, 5) |
Substring | Extracts section from start up to (not including) end. Supports negative indices. |
replace(target, replacement) |
str.replace("a", "b") |
New String | Replaces first match (or all matches if global RegExp or replaceAll used). |
trim() |
str.trim() |
New String | Removes whitespace from both ends of string. |
split(separator) |
str.split(",") |
Array | Splits string into array of substrings based on separator. |
padStart(targetLen, pad) |
str.padStart(4, "0") |
New String | Pads current string with target string until total length reached. |
// Demonstrating practical string manipulation methods
const rawInput = " user_name=Maksudur_Rahman; role=admin ";
// 1. Cleaning and Trimming
const cleanInput = rawInput.trim();
console.log(`Cleaned Input: "${cleanInput}"`);
// 2. Extraction using slice and split
const firstPart = cleanInput.slice(0, 9); // "user_name"
console.log(`Extracted Slice: "${firstPart}"`);
const keyValuePairs = cleanInput.split("; ");
console.log("Split Pairs Array:", keyValuePairs);
// 3. String Replacement
const sanitizedRole = cleanInput.replaceAll("_", " ");
console.log(`Replaced Underscores: "${sanitizedRole}"`);
// 4. Number Padding (Formatting invoice IDs)
const invoiceNumber = 42;
const formattedInvoice = String(invoiceNumber).padStart(6, "0");
console.log(`Formatted Invoice Code: INV-${formattedInvoice}`); // INV-000042
// 5. Case Transformations
console.log(`Upper Case: ${"kodersolution".toUpperCase()}`);
slice() Over substring(): slice() accepts negative indices (counting backwards from string end), making it more versatile than substring().replaceAll() for Global Substitutions: Plain replace("a", "b") replaces only the FIRST match. Use replaceAll() or a global RegExp /a/g.String(val) before invoking padStart() or padEnd() on numeric values.Format the number 7 as a 3-digit string "007" using padStart().
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.