đź§µ String Patterns: The Art of Text Magic
Imagine you have a box of letter beads. You can arrange them, count them, flip them around, and even find hidden patterns. That’s what string processing is all about—playing with text like a word wizard!
🎯 What You’ll Learn
In this adventure, we’ll explore:
- Strings Fundamentals — What strings are and how they work
- String Manipulation — Changing and transforming text
- String Compression — Making text shorter and smarter
- Anagram Detection — Finding word twins that share letters
- Palindrome Detection — Discovering words that read the same backwards
- Longest Palindromic Substring — Finding the biggest hidden mirror inside text
📦 Part 1: Strings Fundamentals
What is a String?
Think of a string like a necklace of letter beads. Each bead is one character, and they’re all connected in order.
let greeting = "Hello";
// H-e-l-l-o (5 beads!)
Key String Properties
Length — How many beads on your necklace?
let word = "JavaScript";
console.log(word.length);
// Output: 10
Accessing Characters — Pick any bead by its position!
let name = "Alice";
console.log(name[0]); // "A"
console.log(name[2]); // "i"
đź’ˇ Remember: Positions start at 0, not 1. The first letter is at position 0!
Strings are Immutable — You can’t change a bead once it’s on the necklace. You have to make a new necklace.
let word = "cat";
word[0] = "b"; // This does nothing!
console.log(word); // Still "cat"
// Make a new string instead
let newWord = "b" + word.slice(1);
console.log(newWord); // "bat"
graph TD A["String: 'Hello'"] --> B["Index 0: H"] A --> C["Index 1: e"] A --> D["Index 2: l"] A --> E["Index 3: l"] A --> F["Index 4: o"]
đź”§ Part 2: String Manipulation
The Toolbox of Text Tricks
Now let’s learn how to change, combine, and transform strings!
Splitting — Break the necklace into pieces
let sentence = "I love coding";
let words = sentence.split(" ");
console.log(words);
// ["I", "love", "coding"]
Joining — Put pieces back together
let parts = ["one", "two", "three"];
let result = parts.join("-");
console.log(result);
// "one-two-three"
Reversing — Flip the necklace around!
let word = "hello";
let reversed = word.split("")
.reverse()
.join("");
console.log(reversed);
// "olleh"
Changing Case
let mixed = "HeLLo WoRLD";
console.log(mixed.toLowerCase());
// "hello world"
console.log(mixed.toUpperCase());
// "HELLO WORLD"
Finding and Replacing
let text = "I like cats";
let newText = text.replace("cats", "dogs");
console.log(newText);
// "I like dogs"
Trimming — Remove extra spaces
let messy = " hello ";
let clean = messy.trim();
console.log(clean);
// "hello"
graph TD A["Original String"] --> B["split#40;#41;"] B --> C["Array of Parts"] C --> D["reverse#40;#41;"] D --> E["Reversed Array"] E --> F["join#40;#41;"] F --> G["New String"]
🗜️ Part 3: String Compression
Making Text Smaller and Smarter
Imagine you have to tell your friend: “AAAAABBBCC”
That’s 10 letters. But what if you said: “A5B3C2”?
That’s only 6 characters — and it means the same thing!
How It Works
We count repeated characters and write: letter + count
function compress(str) {
let result = "";
let count = 1;
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i + 1]) {
count++;
} else {
result += str[i] + count;
count = 1;
}
}
return result;
}
console.log(compress("AAAAABBBCC"));
// "A5B3C2"
When Compression Doesn’t Help
console.log(compress("ABCD"));
// "A1B1C1D1" — longer than "ABCD"!
đź’ˇ Pro Tip: Only use compression when the result is actually shorter!
graph TD A["AAAAABBBCC"] --> B["Count runs"] B --> C["A appears 5 times"] B --> D["B appears 3 times"] B --> E["C appears 2 times"] C --> F["A5B3C2"] D --> F E --> F
🔄 Part 4: Anagram Detection
Finding Word Twins
An anagram is when two words have the exact same letters, just in a different order.
Examples:
- “listen” ↔ “silent” ✅
- “evil” ↔ “vile” ✅
- “hello” ↔ “world” ❌
The Simple Trick
Sort both words alphabetically. If they match, they’re anagrams!
function areAnagrams(str1, str2) {
// Remove spaces, make lowercase
let clean1 = str1.toLowerCase()
.replace(/\s/g, "");
let clean2 = str2.toLowerCase()
.replace(/\s/g, "");
// Sort and compare
let sorted1 = clean1.split("")
.sort()
.join("");
let sorted2 = clean2.split("")
.sort()
.join("");
return sorted1 === sorted2;
}
console.log(areAnagrams("listen", "silent"));
// true
The Faster Way — Character Counting
function areAnagramsFast(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
let count = {};
for (let char of str1) {
count[char] = (count[char] || 0) + 1;
}
for (let char of str2) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
graph TD A["listen"] --> B["Sort: eilnst"] C["silent"] --> D["Sort: eilnst"] B --> E{"Match?"} D --> E E -->|Yes| F["Anagrams! âś…"]
🪞 Part 5: Palindrome Detection
Words That Read the Same Backwards
A palindrome is a word or phrase that reads the same forwards and backwards.
Examples:
- “racecar” → “racecar” ✅
- “madam” → “madam” ✅
- “hello” → “olleh” ❌
The Simple Check
function isPalindrome(str) {
// Clean the string
let clean = str.toLowerCase()
.replace(/[^a-z0-9]/g, "");
// Compare with reverse
let reversed = clean.split("")
.reverse()
.join("");
return clean === reversed;
}
console.log(isPalindrome("racecar"));
// true
console.log(isPalindrome("A man a plan a canal Panama"));
// true
The Two-Pointer Trick — Faster!
Instead of making a new string, check from both ends:
function isPalindromeFast(str) {
let clean = str.toLowerCase()
.replace(/[^a-z0-9]/g, "");
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) {
return false;
}
left++;
right--;
}
return true;
}
graph TD A["racecar"] --> B["Left: r"] A --> C["Right: r"] B --> D{"r = r?"} C --> D D -->|Yes| E["Move inward"] E --> F["Continue checking..."] F --> G["All match! âś…"]
🏆 Part 6: Longest Palindromic Substring
Finding the Biggest Mirror Inside a Word
Sometimes a string has a palindrome hiding inside it!
Example: In “babad”
- “bab” is a palindrome ✅
- “aba” is also a palindrome ✅
- Both are length 3
The “Expand Around Center” Technique
Think of each character as the center of a potential mirror. Then expand outward to find how big the mirror is.
function longestPalindrome(s) {
if (s.length < 2) return s;
let start = 0;
let maxLen = 1;
function expand(left, right) {
while (
left >= 0 &&
right < s.length &&
s[left] === s[right]
) {
let len = right - left + 1;
if (len > maxLen) {
start = left;
maxLen = len;
}
left--;
right++;
}
}
for (let i = 0; i < s.length; i++) {
expand(i, i); // Odd length
expand(i, i + 1); // Even length
}
return s.substring(start, start + maxLen);
}
console.log(longestPalindrome("babad"));
// "bab" or "aba"
console.log(longestPalindrome("cbbd"));
// "bb"
Why Two Expansions?
Palindromes can have an odd or even length:
- Odd: “aba” — center is “b”
- Even: “abba” — center is between “b” and “b”
graph TD A["String: forgeeksskeegfor"] --> B["Try each center"] B --> C["Expand outward"] C --> D["Find: geeksskeeg"] D --> E["Length: 10"] E --> F["Longest! 🏆"]
🎉 Summary: Your String Superpowers
| Concept | What It Does | Example |
|---|---|---|
| Fundamentals | Access and understand strings | "Hello"[0] → “H” |
| Manipulation | Transform text | "abc".split("") |
| Compression | Shorten repeated chars | “AAABB” → “A3B2” |
| Anagram | Same letters, different order | listen ↔ silent |
| Palindrome | Reads same backwards | racecar |
| Longest Palindrome | Biggest mirror in text | “cbbd” → “bb” |
🚀 Key Takeaways
- Strings are like bead necklaces — ordered, indexed, and immutable
- Split, reverse, join is your best friend for transformations
- Compression counts consecutive identical characters
- Anagrams share the same letter counts
- Palindromes are mirrors — check from both ends
- Expand from center to find the longest palindromic substring
You’re now a String Pattern Master! 🧙‍♂️✨
