String Extraction
Overview
Extracting specific parts (substrings) of a string is one of the most common tasks in programming. JavaScript provides three primary methods for this: slice(), substring(), and the deprecated substr().
While they seem similar, they handle edge cases (like negative indexes) very differently. Modern JavaScript development almost exclusively relies on slice() due to its predictability and support for negative indexing.
Syntax
const text = "Apple, Banana, Kiwi";
// slice(startIndex, endIndex) - Note: endIndex is NOT included!
console.log(text.slice(7, 13)); // "Banana"
// If you omit the endIndex, it slices to the very end
console.log(text.slice(7)); // "Banana, Kiwi"
// Negative indexing counts BACKWARDS from the end of the string
console.log(text.slice(-4)); // "Kiwi"const text = "Apple, Banana, Kiwi";
console.log(text.substring(7, 13)); // "Banana"
// WARNING: substring treats negative indexes as ZERO
console.log(text.substring(-4)); // "Apple, Banana, Kiwi" (Started at 0!)Common Pitfalls
- Using negative indexes with
substring(). Becausesubstring()treats all negative numbers as0, it will start extracting from the very beginning of the string, completely breaking your logic. Always useslice().
Interview Questions
slice() and substring()?The main difference is how they handle negative arguments. slice() accepts negative indices and counts backward from the end of the string. substring() treats negative indices as 0.
Real-World Example
Obscuring the first 12 digits of a credit card for security on a checkout page.
const rawCard = "1234567890123456";
// Grab the last 4 digits
const lastFour = rawCard.slice(-4);
const safeCardDisplay = "**** **** **** " + lastFour;Check Your Knowledge
Test your understanding of String Extraction with these quick questions.