JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
153: Using Regex with String Methods
One of the most frustrating moments I see developers hit when they start mixing Regular Expressions with string methods is the "Why did it only do it once?" bug. You'll write a line of code to clean up a string, test it with a simple case, and it works perfectly. Then, you hit production with real-world data, and you realize your code only touched the first occurrence of the pattern and ignored the rest.
The "First Match Only" Trap
It happens most often with .replace(). If you pass a string as the first argument, JavaScript treats it as a literal string and stops the moment it finds a match. Look at this:
const dirtyPhoneNumber = "555-123-4567";
const cleaned = dirtyPhoneNumber.replace("-", "");
console.log(cleaned); // "555123-4567"
You were probably expecting "5551234567", right? But .replace() saw the first hyphen, swapped it for an empty string, and decided its job was done. This is where a lot of learners get stuck—they assume the method behaves like "Replace All" by default.
Unlocking Global Control with /g
To fix this, you have to stop passing a string and start passing a Regular Expression literal. By adding the g (global) flag, you're telling JavaScript: "Don't stop at the first one; find every single instance that matches this pattern."
const dirtyPhoneNumber = "555-123-4567";
const cleaned = dirtyPhoneNumber.replace(/-/g, "");
console.log(cleaned); // "5551234567"
I personally prefer this over .replaceAll() in many cases because it allows you to be more flexible. For instance, what if the user entered the number with dots, spaces, or dashes? A string argument can't handle that, but a Regex can.
const messyInput = "555.123 4567";
const standardized = messyInput.replace(/[\.\s-]/g, "");
console.log(standardized); // "5551234567"
Splitting by More Than One Character
Another powerful combo is using Regex inside .split(). Usually, we split by a single comma or a space. But in the real world, data is messy. Imagine you're parsing a list of tags where some users used commas, some used semicolons, and some used pipes.
If you use .split(','), you'll miss all the semicolons. Instead, use a character class in your Regex:
const tags = "javascript,typescript;react|node";
const tagArray = tags.split(/[,;|]/);
console.log(tagArray); // ["javascript", "typescript", "react", "node"]
This is infinitely cleaner than chaining multiple .replace() calls just to get your delimiters to match before splitting.
Extracting Data with .match()
Finally, there's .match(). While .test() just tells you if a pattern exists (true/false), .match() actually hands you the data. If you use it without the g flag, it gives you a detailed array containing the match and its capturing groups. If you add the g flag, it simply returns an array of every match it found.
const logEntry = "Error: 404 at 12:00, Error: 500 at 12:05";
const allErrors = logEntry.match(/Error: \d+/g);
console.log(allErrors); // ["Error: 404", "Error: 500"]
Just a heads up: be careful with .match(). If no matches are found, it returns null, not an empty array. Always check for existence before trying to map or filter the results, or you'll trigger a TypeError that crashes your app.
📋 Practical Task
Building a Messy CSV Row Sanitizer
You are processing a CSV-like string where the delimiters are inconsistent (sometimes commas, sometimes tabs, sometimes semicolons) and the values often have annoying leading or trailing whitespace.
Your Task: Write a function sanitizeRow(row) that does the following:
- Splits the string into an array using a Regular Expression that recognizes commas (
,), semicolons (;), or tabs (\t) as delimiters. - Uses
.map()and.replace()with a global Regular Expression to trim whitespace from the beginning and end of every resulting string in the array.
Test Case:
const input = " John Doe , 30 ; Software Engineer \t New York ";
// Expected output: ["John Doe", "30", "Software Engineer", "New York"]There are no comments for now.