JavaScript Programming Labs

Master JavaScript through hands-on coding challenges. Write real code, get instant feedback, and build practical web development skills.

Regular Expressions, Dates & JSON - Module 7

Master pattern matching with regex, work with dates and times, and handle JSON data.

Lab 19: Regular Expressions
Advanced
Coding Challenge
Your Task: Master Regular Expressions (RegEx) - powerful pattern matching tools for searching, validating, and manipulating strings.

Detailed Requirements:

1. Create a RegEx pattern - Using literal syntax or RegExp constructor.
// Literal syntax (preferred for static patterns) const pattern1 = /hello/; const pattern2 = /hello/gi; // g=global, i=case-insensitive // Constructor (for dynamic patterns) const pattern3 = new RegExp("hello"); const pattern4 = new RegExp("hello", "gi");
2. Use test() to check for matches - Returns true/false.
const emailPattern = /^[\w.-]+@[\w.-]+\.\w+$/; console.log(emailPattern.test("user@example.com")); // true console.log(emailPattern.test("invalid-email")); // false const phonePattern = /^\d{3}-\d{3}-\d{4}$/; console.log(phonePattern.test("123-456-7890")); // true
3. Use match() to find matches - Returns array of matches or null.
const text = "The rain in Spain falls mainly in the plain"; // Without global flag - returns first match with details const match1 = text.match(/ain/); console.log(match1); // ["ain", index: 5, ...] // With global flag - returns all matches const match2 = text.match(/ain/g); console.log(match2); // ["ain", "ain", "ain", "ain"]
4. Use replace() to substitute matches - Replace matched patterns.
const text = "Hello World"; // Replace first match console.log(text.replace(/o/, "0")); // "Hell0 World" // Replace all matches (global flag) console.log(text.replace(/o/g, "0")); // "Hell0 W0rld" // With capture groups const name = "John Smith"; console.log(name.replace(/(\w+) (\w+)/, "$2, $1")); // "Smith, John"
5. Use common patterns and character classes
// Character classes \d // Digit [0-9] \w // Word char [a-zA-Z0-9_] \s // Whitespace . // Any character except newline // Quantifiers * // 0 or more + // 1 or more ? // 0 or 1 {n} // Exactly n {n,m} // Between n and m // Anchors ^ // Start of string $ // End of string \b // Word boundary
6. Use capture groups and split()
// Capture groups with parentheses const dateStr = "2024-01-15"; const dateMatch = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/); console.log(dateMatch[1]); // "2024" (year) console.log(dateMatch[2]); // "01" (month) console.log(dateMatch[3]); // "15" (day) // Split by pattern const csv = "apple,banana;orange|grape"; const fruits = csv.split(/[,;|]/); console.log(fruits); // ["apple", "banana", "orange", "grape"]
💡 Pro Tips:
• Use regex101.com to test and debug patterns
• Escape special characters with backslash: \. \* \? \+ \( \)
• Use i flag for case-insensitive matching
• Use g flag to find all matches
• Named capture groups: (?<name>\d+)

⚠️ Common Mistakes to Avoid:
• Forgetting to escape special characters
• Not using global flag when replacing all occurrences
• Overly complex patterns (keep it simple)

Expected Output:
Email valid: true Phone matches: ["123-456-7890"] Replaced: Hell0 W0rld Split words: ["apple", "banana", "orange"] Capture groups: year=2024, month=01

Requirements Checklist

Create a RegEx pattern (literal or constructor)
Use test() to check for matches
Use match() to find matches
Use replace() with a RegEx pattern
Use character classes (\d, \w, \s)
Use capture groups with parentheses
Console Output
// Click "Run Code" to execute your JavaScript
Hints & Tips
• Create pattern: /pattern/ or new RegExp("pattern")
• Test: pattern.test(string) → true/false
• Match: string.match(pattern) → array or null
• Replace: string.replace(pattern, replacement)
• Character classes: \d (digit), \w (word), \s (space)
• Capture: /(\d+)-(\d+)/ → match[1], match[2]
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 20: Date & Time
Intermediate
Coding Challenge
Your Task: Learn to work with dates and times in JavaScript using the Date object. Handle timestamps, format dates, and perform date arithmetic.

Detailed Requirements:

1. Create Date objects - Multiple ways to create dates.
// Current date/time const now = new Date(); console.log(now); // Current date and time // From string (ISO 8601 format recommended) const date1 = new Date("2024-01-15"); const date2 = new Date("2024-01-15T10:30:00"); // From components (month is 0-indexed!) const date3 = new Date(2024, 0, 15); // Jan 15, 2024 const date4 = new Date(2024, 0, 15, 10, 30, 0); // 10:30:00 // From timestamp (milliseconds since Jan 1, 1970) const date5 = new Date(1705312200000);
2. Get date components - Extract parts of a date.
const date = new Date("2024-01-15T10:30:45"); console.log(date.getFullYear()); // 2024 console.log(date.getMonth()); // 0 (January - 0-indexed!) console.log(date.getDate()); // 15 console.log(date.getDay()); // Day of week (0=Sun, 6=Sat) console.log(date.getHours()); // 10 console.log(date.getMinutes()); // 30 console.log(date.getSeconds()); // 45 console.log(date.getTime()); // Timestamp in milliseconds
3. Set date components - Modify parts of a date.
const date = new Date(); date.setFullYear(2025); date.setMonth(5); // June (0-indexed) date.setDate(20); date.setHours(14); date.setMinutes(30); date.setSeconds(0); console.log(date); // June 20, 2025 14:30:00
4. Format dates - Convert to readable strings.
const date = new Date("2024-01-15T10:30:00"); // Built-in methods console.log(date.toDateString()); // "Mon Jan 15 2024" console.log(date.toTimeString()); // "10:30:00 GMT+0000" console.log(date.toLocaleDateString()); // "1/15/2024" (locale-dependent) console.log(date.toLocaleTimeString()); // "10:30:00 AM" console.log(date.toISOString()); // "2024-01-15T10:30:00.000Z" // With options date.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" }); // "Monday, January 15, 2024"
5. Date arithmetic - Add/subtract time.
const now = new Date(); // Add days const tomorrow = new Date(now); tomorrow.setDate(now.getDate() + 1); // Add hours const later = new Date(now); later.setHours(now.getHours() + 3); // Difference between dates (in milliseconds) const date1 = new Date("2024-01-01"); const date2 = new Date("2024-01-15"); const diffMs = date2 - date1; const diffDays = diffMs / (1000 * 60 * 60 * 24); console.log("Difference:", diffDays, "days"); // 14
6. Compare dates and get timestamps
const date1 = new Date("2024-01-15"); const date2 = new Date("2024-01-20"); // Compare using getTime() or direct comparison console.log(date1 < date2); // true console.log(date1.getTime() < date2.getTime()); // true // Get current timestamp const timestamp = Date.now(); // Milliseconds since epoch console.log(timestamp); // Create date from timestamp const dateFromTs = new Date(timestamp);
💡 Pro Tips:
• Months are 0-indexed (0 = January, 11 = December)
• Use Date.now() for current timestamp (faster than new Date().getTime())
• Store dates as ISO strings or timestamps for consistency
• Consider using libraries like date-fns or Luxon for complex operations
• Be aware of timezone issues with UTC vs local time

⚠️ Common Mistakes to Avoid:
• Forgetting months are 0-indexed
• Mutating date objects instead of creating new ones
• Ignoring timezones when comparing dates

Expected Output:
Current date: Mon Jan 15 2024 Year: 2024, Month: 0, Day: 15 Formatted: January 15, 2024 Tomorrow: Tue Jan 16 2024 Days between: 14

Requirements Checklist

Create a new Date object
Use getter methods (getFullYear, getMonth, etc.)
Use setter methods (setFullYear, setDate, etc.)
Format a date using toLocaleDateString or similar
Perform date arithmetic (add/subtract days)
Compare two dates or use getTime()/Date.now()
Console Output
// Click "Run Code" to execute your JavaScript
Hints & Tips
• Create: new Date(), new Date("2024-01-15")
• Get: getFullYear(), getMonth(), getDate()
• Set: setFullYear(), setMonth(), setDate()
• Format: toDateString(), toLocaleDateString()
• Add days: date.setDate(date.getDate() + n)
• Timestamp: Date.now(), date.getTime()
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 21: JSON (JavaScript Object Notation)
Intermediate
Coding Challenge
Your Task: Master JSON - the universal data interchange format. Learn to parse, stringify, and work with JSON data effectively.

Detailed Requirements:

1. Parse JSON strings with JSON.parse() - Convert JSON string to JavaScript object.
const jsonString = '{"name": "John", "age": 30, "city": "NYC"}'; const user = JSON.parse(jsonString); console.log(user.name); // "John" console.log(user.age); // 30 // Parse array const arrayJson = '[1, 2, 3, "four", true]'; const arr = JSON.parse(arrayJson); console.log(arr[0]); // 1
2. Stringify objects with JSON.stringify() - Convert JavaScript object to JSON string.
const user = { name: "John", age: 30, email: "john@example.com" }; const jsonStr = JSON.stringify(user); console.log(jsonStr); // '{"name":"John","age":30,"email":"john@example.com"}' // Pretty print with indentation const prettyJson = JSON.stringify(user, null, 2); console.log(prettyJson); /* { "name": "John", "age": 30, "email": "john@example.com" } */
3. Handle nested objects and arrays
const data = { users: [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ], metadata: { total: 2, page: 1 } }; const json = JSON.stringify(data, null, 2); const parsed = JSON.parse(json); console.log(parsed.users[0].name); // "Alice" console.log(parsed.metadata.total); // 2
4. Use replacer function for selective stringify
const user = { name: "John", password: "secret123", email: "john@example.com" }; // Exclude sensitive fields with replacer function const safeJson = JSON.stringify(user, (key, value) => { if (key === "password") return undefined; // Omit this field return value; }); console.log(safeJson); // No password! // Or specify allowed keys as array const filtered = JSON.stringify(user, ["name", "email"]); console.log(filtered); // Only name and email
5. Use reviver function for custom parsing
const jsonWithDate = '{"name": "Event", "date": "2024-01-15T10:30:00.000Z"}'; // Reviver converts date strings to Date objects const event = JSON.parse(jsonWithDate, (key, value) => { if (key === "date") { return new Date(value); } return value; }); console.log(event.date instanceof Date); // true console.log(event.date.getFullYear()); // 2024
6. Handle parse errors with try/catch
function safeJsonParse(jsonString) { try { return JSON.parse(jsonString); } catch (error) { console.error("Invalid JSON:", error.message); return null; } } const valid = safeJsonParse('{"name": "test"}'); console.log(valid); // { name: "test" } const invalid = safeJsonParse("not valid json"); console.log(invalid); // null (error was caught)
💡 Pro Tips:
• JSON only supports: strings, numbers, booleans, null, objects, arrays
• Functions, undefined, and symbols are NOT valid JSON
• Use JSON.stringify(obj, null, 2) for readable output
• Always wrap JSON.parse() in try/catch
• Dates become strings in JSON - use reviver to convert back

⚠️ Common Mistakes to Avoid:
• Not handling parse errors (crashes on invalid JSON)
• Expecting functions/dates to survive stringify/parse
• Circular references (causes stringify to throw)

Expected Output:
Parsed: { name: "John", age: 30 } Stringified: {"name":"John","age":30} Pretty JSON with 2-space indent Nested access: users[0].name = "Alice" Safe parse returned null for invalid JSON

Requirements Checklist

Use JSON.parse() to convert string to object
Use JSON.stringify() to convert object to string
Use pretty printing (JSON.stringify with indentation)
Work with nested objects/arrays
Use replacer or reviver function
Handle JSON errors with try/catch
Console Output
// Click "Run Code" to execute your JavaScript
Hints & Tips
• Parse: JSON.parse(jsonString)
• Stringify: JSON.stringify(object)
• Pretty: JSON.stringify(obj, null, 2)
• Replacer: JSON.stringify(obj, replacerFn)
• Reviver: JSON.parse(str, reviverFn)
• Safe parse: wrap in try { } catch { }
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below