• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops○While Loop○Break and Continue
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods●Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes○Inheritance○Encapsulation
○Asynchronous JavaScript○Promises and Async Await○Async API Simulation

Regular Expressions

A regular expression (regex) is a pattern that describes a set of strings. JavaScript has built-in regex support for searching, validating, and transforming strings.

Creating a regex

javascript
// Literal syntax (preferred)
const pattern = /hello/i;   // i = case-insensitive

// Constructor (for dynamic patterns)
const word = "hello";
const dynamic = new RegExp(word, "i");

Common special characters

PatternMeaning
.Any character except newline
\dDigit (0-9)
\wWord character (letter, digit, _)
\sWhitespace
^Start of string
$End of string
*0 or more
+1 or more
?0 or 1
{n,m}Between n and m
[abc]Character class
[^abc]Negated class

Key methods

javascript
// test() — returns boolean
/^\d{5}$/.test("12345");  // true — zip code
/^\d{5}$/.test("1234");   // false

// match() — returns array of matches
"I have 3 cats and 12 dogs".match(/\d+/g); // ["3", "12"]

// replace() — string substitution
"hello world".replace(/\b\w/g, c => c.toUpperCase()); // "Hello World"

// split() with regex
"one,  two,   three".split(/,\s*/); // ["one", "two", "three"]

Your Task

  1. Write a function isValidEmail(email) that returns true if email matches the basic pattern name@domain.tld (use regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/).
  2. Write a function extractNumbers(text) that returns an array of all number strings found in text.
  3. Write a function maskEmail(email) that hides all but the first character of the local part, e.g. "alice@example.com" → "a****@example.com".
  4. Display in #output: "valid: true | numbers: 3,12 | masked: a****@example.com".
Hint 1
1 / 3
HINT 1

Test a pattern: pattern.test(str) returns true/false.

Loading editor…
READY
intercourses
javascript