30 Days of JavaScript: Regular Expressions in JavaScript, Day 9

30 Days of JavaScript: Building a Simple Weather App
30 Days of JavaScript: Regular Expressions in JavaScript, Day 9

Discover the power of Regex in JavaScript! This guide covers pattern matching, form validation, and text manipulation techniques to boost your skills.

You’ve written the loop before. Check whether a string holds a phone number, then a second pass for the dashes, then a third for the country code, and somewhere around the fourth branch you gave up and pasted something off Stack Overflow.

That something was almost certainly a regular expression. Regex is a small language for describing patterns in text, and once it clicks, a dozen lines of string-poking collapse into one. Today we’ll cover enough to be useful: matching a pattern, swapping text, and validating a form field.

Table of Contents

Understanding Regex Patterns

A regex is a mix of ordinary characters and special ones. The ordinary characters match themselves; the special ones describe repetition, position, or choice. So /abc/ matches the exact run “abc”. /ab*c/ is more interesting: the * means “zero or more of the thing right before it,” so it matches “ac”, “abc”, “abbc”, and on up.

The quickest way to ask “does this string fit the pattern” is test(), which hands back a plain true or false.

JS
/**
 * Tests if a string matches a regular expression pattern
 * @param {string} str - The string to be tested against the regex pattern
 * @returns {boolean} - True if the string matches the pattern, false otherwise
 */
let regexPattern = /ab*c/;
let someString = 'abbbc';
let result = regexPattern.test(someString);
console.log(result); // Outputs: true

Here test() checks someString against regexPattern. “abbbc” fits /ab*c/, so you get true.

String Manipulation with Regex

Where regex really earns its keep is find-and-replace across a whole string. Say some text keeps spelling the language name “Javascript” and you want the canonical “JavaScript” everywhere it shows up.

JS
/**
 * Replaces occurrences of a word in a string using regex
 * @param {string} str - The original string
 * @param {string} word - The word to replace
 * @param {string} replacement - The replacement word
 * @returns {string} - The updated string with replacements made
 */
let regexPattern = /Javascript/gi;
let text = 'Javascript is the backbone of modern web development. Javascript is powerful.';
let newText = text.replace(regexPattern, 'JavaScript');
console.log(newText);
// Outputs: JavaScript is the backbone of modern web development. JavaScript is powerful.

replace() swaps every match. Two flags do the heavy lifting here. The g (global) flag tells it to fix every occurrence instead of stopping at the first one, and i (ignore case) means it catches “javascript”, “JAVASCRIPT”, and everything in between.

Form Validation with Regex

Form validation is the classic regex job. You want to reject an obviously malformed email before it ever reaches your server. Here’s a small form that checks the field on submit.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation Example</title>
</head>
<body>
  <form>
    <input type="email" id="email" placeholder="Enter your email">
    <button type="button" onclick="validateEmail()">Submit</button>
  </form>
  <script>
  /**
   * Validates an email address using a regular expression
   * @returns {void} - Displays an alert with the validation result
   */
  function validateEmail() {
    let emailInput = document.getElementById("email").value;
    let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    if (emailRegex.test(emailInput)) {
      alert("Valid email!");
    } else {
      alert("Invalid email. Please enter a correct email address.");
    }
  }
  </script>
</body>
</html>

When the button is clicked, validateEmail() runs the input through the pattern and alerts based on the result.

One honest caveat: no regex fully validates an email, and this one is deliberately loose. The {2,6} at the end caps the top-level domain at six characters, so it quietly rejects real addresses on longer TLDs like .software. Treat a pattern like this as a cheap first filter, not proof the address is real. The only real test is sending mail to it and seeing if it lands.

Conclusion

Regex looks like line noise until it doesn’t. Learn a handful of pieces (the quantifiers, the character classes, the g and i flags) and you can handle most day-to-day text work: validation, search, replacement.

Today we covered pattern matching with test(), bulk replacement with replace(), and a basic form check. Build your patterns up one piece at a time and run them against real strings as you go. That’s how they stop feeling like magic and start feeling like a tool.

What’s Next?

Day 10 is Error Handling and Debugging. We’ll look at catching failures on purpose instead of letting them take down the page, so your code degrades gracefully when something goes sideways. See you there.

Next: 30 Days of JavaScript: Error Handling and Debugging, Day 10

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top