Marcy Lab School Docs
  • Welcome
  • Student Guidelines & Policies
    • Student Handbook
    • AI Policy
    • Academic Calendar
  • Environment Setup
    • Local Environment Setup - Mac
    • Local Environment Setup - Windows
    • GitHub Setup
    • Postgres Setup
  • How-Tos
    • How To Code at Marcy: Code Style Guide
    • How to Do Short Response and Coding Assignments
    • How to Debug
    • How to PEDAC
    • How to Create A GitHub Organization and Scrumboard
    • How to Create Projects with Vite
    • How to Deploy on GitHub Pages
    • How to Deploy on Render
    • How to Test your API with Postman
  • Mod 0 - Command Line Interfaces, Git, and GitHub
    • Overview
    • 1. Command Line Interfaces
    • 2. Git & GitHub
    • 3. Git Pulling & Merging
    • 4. Git Branching & PRs
  • Mod 1 - JavaScript Fundamentals
    • Overview
    • 1. Intro to Programming
    • 2. Errors
    • 3. Node & Node Modules
    • 4. Variables, Functions & String Methods
    • 5. Control Flow, typeof, and Math
    • 6. Loops
    • 7. Arrays
    • 8. Objects
    • 9. Higher Order Functions: Callbacks
    • 10. Higher Order Functions: Array Methods
    • 11. Regex
  • Mod 2 - HTML, CSS & the DOM
    • Overview
    • 1. HTML
    • 2. CSS
    • 3. Accessibility (a11y)
    • 4. The Document Object Model (DOM) API
    • 5. Events
    • 6. Forms
    • 7. The Box Model and Positioning
    • 8. Flexbox
    • 9. Grid & Media Queries
    • 10. ESModules
    • 11. Vite
    • 12. LocalStorage
  • Mod 3 - Async & APIs
    • Overview
    • 1. Promises
    • 2. Fetch
    • 3. Building a Fetching App
    • 4. Async & Await
    • 5. A Generic Fetch Handler
  • Mod 4 - Project Week!
    • Important How Tos and Guides
      • How to Create a GitHub Organization and Scrum Board
      • How To Start a Project with Vite
      • How To Deploy a Project with GitHub Pages
    • Project Week Overview
    • Agile Methodologies
    • Deliverables & Milestones
    • Technical Requirements Checklist
    • Free API List
    • Collaborative GitHub
  • Mod 5 - Object-Oriented Programming
    • Overview
    • 1. Intro to OOP, Encapsulation, Factory Functions, and Closure
    • 2. Classes
    • 3. Private & Static
    • 4. UML Diagrams & Has Many/Belongs To Relationships
    • 5. Challenge: Implementing Has Many/Belongs To
    • 6. Inheritance
    • 7. Polymorphism
    • 8. Review and Practice
    • MDN: Object Prototypes
  • Mod 6 - Data Structures & Algorithms
    • Overview
    • Important How Tos and Guides
      • How to Debug
      • How to PEDAC
    • 1. Nodes & Linked Lists
    • 2. Singly & Doubly Linked Lists
    • 3. Stacks & Queues
    • 4. Recursion
    • 5. Trees
  • Mod 7 - React
    • Overview
    • Important How Tos and Guides
      • How to Create Projects with Vite
      • How to Deploy on GitHub Pages
    • 1. Intro to React
    • 2. Events, State, and Forms
    • 3. Fetching with useEffect
    • 4. React Router
    • 5. Building a Flashcards App
    • 6. React Context
    • 7. Global Context Pattern
  • Mod 8 - Backend
    • Overview
    • Important How Tos and Guides
      • How to Deploy on Render
      • How to Test your API with Postman
      • Postgres Setup
    • 1. Intro to Express
    • 2. Building a Static Web Server with Middleware
    • 3. Securing API Keys and Environment Variables
    • 4. RESTful CRUD API
    • 5. Model-View-Controller Architecture
    • 6. SQL and Databases
    • 7. JOIN (Association) SQL Queries
    • 8. Knex
    • 9. Your First Fullstack App!
    • 10. Migrations & Seeds
    • 11. Schema Design & Normalization
    • 12. Hashing Passwords with Bcrypt
    • 13. React Express Auth Template Overview
  • Mod 9 - Civic Tech Hackathon
    • Overview
    • Rubric
  • Mod 10 - Capstone
    • Overview
Powered by GitBook
On this page
  • Slides
  • Intro
  • What is a Regular Expression
  • What can you do with regular expressions?
  • Regular Expression Syntax
  • There are a lot of cool ways to use regular expressions
  • Special Characters
  • How to Regular Expressions in JavaScript
  • RegExp.test(str) and the i flag
  • str.search(RegExp)
  • str.match(RegExp) and the g flag
  • str.replace(RegExp, replacement)
  1. Mod 1 - JavaScript Fundamentals

11. Regex

Previous10. Higher Order Functions: Array MethodsNextMod 2 - HTML, CSS & the DOM

Last updated 7 months ago

Follow along with code examples !

Use https://regexr.com/ to learn about and test regular expressions!

Table of Contents:

Slides

Intro

Consider this function:

0-intro.js
const isOnlyAlphaNumeric = (str) => {
  if (!str.length) return false;
  const valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'; 
  for (let i = 0; i < str.length; i++) { 
    if (!valid.includes(str[i])) { 
      return false; 
    } 
  }
  return true; 
};

console.log(isOnlyAlphaNumeric('Hello world!'));  // false
console.log(isOnlyAlphaNumeric('Hello_world'));   // true

Now, consider the function with regular expressions.

0-intro.js
const isOnlyAlphaNumericRegex = (str) => /^\w+$/.test(str);

What is a Regular Expression

A regular expression (or "Reg Ex") is a sequence of characters that specifies a "match pattern" to search for strings in text, extract information, or validate input.

To create a regular expression, we use a pair of forward slashes with the match pattern inside.

const regex = /^\w+$/ 
console.log(typeof regex); // object

The symbols and characters inside of the / / define the characteristics of the strings that the regular expression can be used to search for. In the example above, we have:

  • ^ requires that the matching string must start with...

  • \w+ one or more word characters (letters, numbers, or _).

    • The \w represents a word character and the + modifier means "one or more"

  • $ requires that the matching string must end before any other characters are included (no spaces, no symbols, nothing!)

What can you do with regular expressions?

Validate Strings

Like the isOnlyAlphaNumeric function, regular expressions are often used to validate if a string matches a specific pattern.

One of the most common challenges in applications is validating proper date formats. This function uses a regular expression to ensure that a given string is in the "MM-DD-YYYY" format:

1-isValidDate.js
const isValidDateStr = (dateStr) => {
  // requires 'MM-DD-YYYY' formatted date strings
  const dateRegExp = /^(0[1-9]|1[0-2])-([0-2][0-9]|3[01])-[0-9]{4}$/;
  return dateRegExp.test(dateStr);
}

console.log(isValidDateStr('10-12-1995'));    // true
console.log(isValidDateStr('a 10-12-1995'));  // false
console.log(isValidDateStr('12-32-2024'));    // false

Extract Strings From Text

One cool usage of regular expressions is to "find all instances of X in a string". For example, in a big block of text, grab all of the emails:

0-intro.js
const extractEmails = (text) => {
  const emailRegExp = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;
  return text.match(emailRegExp);
}

const message = `
Dear Team,

Thank you for attending the meeting earlier today. As discussed, please reach out to the following team members if you have any questions or need further clarification:

For project management updates, contact Sarah at sarah.jones@example.com.
For technical issues, reach out to Mike at mike.smith@example.com.
For client communications, please email Julia at julia.roberts@example.com.
Let me know if you need anything else.

Best regards,
John
john.doe@example.com
`

const emails = extractEmails(message);
console.log(emails);

/* 
[
  'sarah.jones@example.com',
  'mike.smith@example.com',
  'julia.roberts@example.com',
  'john.doe@example.com'
]
*/

Regular Expression Syntax

There are a lot of cool ways to use regular expressions

Here are some snippets to get started!

Name

Info

Example

Flags

g=global, I=insensitive

/cat/gi

letters

You know letters

/dog/

digits

You know digits

/12/

Character Set/Class

Brackets

/[aeiou]/

Negated Character Set

Carrot and brackets

/[^aeiou]/

O or more

*

/a*/

1 or more

+

/a+/

0 or 1

?

/a?/

Or

|

/cat|dog/

Start of string

Carrot, no brackets

/^hi/

End of string

Dollar sign

/bye$/

Quantifier exactly

Braces, one number

/AH{10}/

Quantifier at least X many

Braces, one number and comma

/OH{3,}/

Quantifier exact range

Braces, two comma separated numbers

/WO{2,4}W/

Groups

Parens with optional pipe OR operator

/(my)\s(cat|dog)/

Special Characters

Character Class
Definition

[0-9]

Any single digit

[3-30]

And number in range

[a-z]

Any lowercase letter

[a-d]

Any lowercase letter in range

[A-Z]

Any uppercase letter

[E-Q]

Any uppercase letter

[a-zA-Z]

Any letter

\d

Any single digit

\D

Any NON digit

\w

Any alphanumeric (and _)

\W

Any NON alphanumeric

\s

Any whitespace character

\S

Any NON whitespace character

\b

Any word break

\B

Any NON word break

.

Any character at all

\.

An escaped period

How to Regular Expressions in JavaScript

The methods to be aware of that utilize regular expressions are:

  1. RegExp.test(str) - validate that a string has a match

  2. str.search(RegExp) - find the index of a match in a string

  3. str.match(RegExp) - find one or more matches in a string

  4. str.replace(RegExp, replacement) - replace one or more matches in a string

Note that the first method is invoked on a regular expression and the input is a string while the other two are invoked on a string and the input is a regular expression.

RegExp.test(str) and the i flag

The RegExp.test(str) returns true if there is a match between the regular expression and the given string.

const catRegEx = /cat/ 

catRegEx.test("the cat in the hat"); // Returns true
catRegEx.test("the dog in the hat"); // Returns false because no "cat"
catRegEx.test("the Cat in the hat"); // Returns false because of case sensitivity

By default, regular expressions are case sensitive and, unless otherwise specified, must be an exact match.

Adding the i flag after the second / allows for case-insensitive matches:

// Add the i flag after the second /
const catRegEx = /cat/i 

catRegEx.test("the cat in the hat"); // Returns true
catRegEx.test("the Cat in the hat"); // Also returns true

str.search(RegExp)

str.search(RegExp) returns the index of the first match between the string and the given regular expression, or -1 if none exist.

const phrase = 'How now brown cow?'
phrase.search(/brow/);  // Returns 8
phrase.search(/ow/);    // Returns 1

str.match(RegExp) and the g flag

str.match(RegExp) returns an array containing matches between the string and the given regular expression.

const phrase = 'My cat named caterpillar loves catnip.'
const firstMatch = phrase.match(/cat/);
console.log(firstMatch);
/* 
[
  'cat',
  index: 3,
  input: 'My cat named caterpillar loves catnip.',
  groups: undefined
]
*/

// Without the global flag, match will only return the first match
console.log(firstMatch.length); // Prints 1
console.log(firstMatch[0]);     // Prints 'cat'
console.log(firstMatch.index);  // Prints 3

The returned array is a little bit strange looking at first but its just an array with one value, and then the properties index, input, and groups

By default, regular expressions will stop searching after the first match is found. Adding the global g flag after the second / causes match to return ALL matches.

// With the global flag:
const allMatches = phrase.match(/ow/g);
console.log(allMatches);        // Prints ['ow', 'ow', 'ow', 'ow'];
console.log(allMatches.length); // Prints 4

str.replace(RegExp, replacement)

str.replace(RegExp, replacement) replaces matches between the string the given regular expression with the given replacement string.

const phrase = "my cat is named Catherine";

// Replace only the first "cat", regardless of case
const newPhrase = phrase.replace(/cat/i, 'dog');

console.log(newPhrase); // Prints 'my dog is named Catherine'

By default, replace will only replace the first match. You can use the g flag to replace ALL matches.

const phrase = "my cat is named Catherine";

// Replace all "cat"s regardless of case, not just the first one
const newPhrase = phrase.replace(/cat/gi, 'dog');

console.log(newPhrase); // Prints 'my dog is named dogherine'
here
Slides
Intro
What is a Regular Expression
What can you do with regular expressions?
Validate Strings
Extract Strings From Text
Regular Expression Syntax
There are a lot of cool ways to use regular expressions
Special Characters
How to Regular Expressions in JavaScript
RegExp.test(str) and the i flag
str.search(RegExp)
str.match(RegExp) and the g flag
str.replace(RegExp, replacement)