topskill.dev
CoursesTracks
0
All courses/Introduction to JavaScriptRegular Expressions
Strings and Regular Expressions
3 / 8
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking○Missing values and deliberate emptiness○Inspect Values in the Console○Inspect the Queue Report○Trace a Faulty Calculation○Repair the Score Calculation✦Module Quiz
○Declaring Variables○let and const in Practice○Operators○Type Conversion○Group and Convert Expense Inputs○Calculate the Event Expense Total○Track a Changing Points Tally○Adjust a Ticket Price✦Module Quiz
○Comparisons and strict equality○Truthiness and combined conditions○Function inputs and results○Conditionals○Combined Conditions Before FizzBuzz○Challenge: FizzBuzz Announcer○Switch Statement○Switch a Venue Sign○Challenge: Power Loadout○For Loops○While Loop○Break and Continue○Stop a Ticket Scan○Challenge: Number Guess Referee○Rainfall Routing Walkthrough○Score Batch Report✦Module Quiz
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions○Ticket Pricing Walkthrough○Shipping Labels with Defaults○Seat Ledger Closure Walkthrough○Private Budget Ledger✦Module Quiz
○Arrays○Student Scoreboard○Challenge: Student Course Scoreboard○Array Mutation Methods○Array Slice and Concat○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○Charging Rack Restock Report○Pantry Restock Plan✦Module Quiz
○Object Key-Value Pairs○Student Course Record○Object Methods and Destructuring○Object copies and optional properties○Map and Set Collections○Playlist Lookup○Number and BigInt Boundaries○Ticket Ledger○JSON○Throwing and catching errors○Math and Date○Date Basics○Supply Bin Audit○Volunteer Shift Audit○Workshop Attendance Feed○Parcel Scan Feed✦Module Quiz
○String Methods○Template Literals●Regular Expressions○Build a Reminder with Template Literals○Format Pantry Pickup Messages○Validate a Time Slot with Regex○Validate Storage Shelf Labels✦Module Quiz
○Higher-Order Functions○Callbacks○map, filter, and reduce○Student Register with map○Challenge: Student Register○Recursion○Project - Data Transform Pipeline○Extend the inventory report○Handle an Error-First Callback○Report Seat Reservation Results○Summarize Completed Bike Rides○Summarize Delivered Parcels✦Module Quiz
○A notebook object○OOP Introduction○Independent workshop passes○Classes○An inherited notice○Inheritance○A private seat counter○Encapsulation○Equipment desk checkout○Project: Library Checkout✦Module Quiz
○Callback Timing○Asynchronous JavaScript○Promise Rehearsal○Promises and Async Await○Offline API Coordination○Async API Simulation○Partial Results Bulletin○Project: Resilient Awards Feed○Retry a Local Delivery○Project: Reliable Score Delivery✦Module Quiz

Regular Expressions

A regular expression, or regex, describes a text pattern. Use one when a substring search is too loose, such as checking the shape of an email-like address or finding digit sequences inside a sentence.

Read the pattern before using it

A regex literal goes between slashes: /hello/i. The slashes mark the pattern's boundaries; they are not part of the text to match. The optional i flag ignores letter case. Without it, /hello/ does not match "HELLO".

SyntaxMeaning in these examples
\dOne digit from 0 to 9
\sOne whitespace character
[abc]One character from the listed choices
[^abc]One character not among those choices
+One or more of the preceding item
{5}Exactly five of the preceding item
^ and $Start and end of input (without the m flag)
\.A literal dot; an unescaped . matches almost any character

For example, /^\d{5}$/ requires five digits and nothing else. The ^ outside brackets anchors the start; inside [^abc], it has a different job: excluding characters.

javascript
console.log(/^\d{5}$/.test("12345"));
console.log(/^\d{5}$/.test("1234"));
console.log("3 cats and 12 dogs".match(/\d+/g));

pattern.test(text) returns a boolean. text.match(pattern) with g (global) finds all matches as an array of strings, or returns null when there are none. text.match(/\d+/g) || [] replaces that no-match result with an empty array. Here a "number" means a digit sequence: signs and decimal points are not part of the match.

For email shape, read /^[^\s@]+@[^\s@]+\.[^\s@]+$/ in pieces: one or more non-whitespace, non-@ characters; an @; another such group; a literal dot; and a final group. Use this pattern without g: repeated yes/no tests should not carry a remembered search position. The anchors rule out extra text. This intentionally basic pattern is not a complete email standard and cannot tell whether an address exists.

Mask a local part

email.split("@") separates an address into a local part and domain. Array destructuring can name them: const [local, domain] = email.split("@");. Read the first character with local[0]; "*".repeat(n) creates n asterisks. For masking, assume one @ and a nonempty local part. A one-character local part needs zero asterisks.

Edit script.js. Supplied checks cover valid and invalid shapes, no matches, and several mask lengths. Keep the checks, Run to inspect them, then Submit.

Your Task

  1. Complete isValidEmail(email) using /^[^\s@]+@[^\s@]+\.[^\s@]+$/ and return its boolean test result.
  2. Complete extractNumbers(text) to return every digit-sequence string with /\d+/g, or [] when none occur.
  3. Complete maskEmail(email) to retain the first local-part character, replace the rest with *, and keep the domain.
  4. Log valid: true | numbers: 3,12 | masked: a****@example.com on a separate line using your helpers with "[email protected]" and "I have 3 cats and 12 dogs".
Hint 1
1 / 3
HINT 1

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

HINT 2

Find matches: str.match(pattern) returns an array or null.

HINT 3

Use flags: g for global, i for case-insensitive.

Files
  • ⋄script.js
Loading editor…
Press Run to execute your code.