Skip to Content
Course content

153: Using Regex with String Methods

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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"]
Rating
0 0

There are no comments for now.

to be the first to leave a comment.