Master JavaScript through hands-on coding challenges. Write real code, get instant feedback, and build practical web development skills.
Master pattern matching with regex, work with dates and times, and handle JSON data.
// 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");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")); // trueconst 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"]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"// 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// 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"]\. \* \? \+ \( \)i flag for case-insensitive matchingg flag to find all matches(?<name>\d+)Email valid: true
Phone matches: ["123-456-7890"]
Replaced: Hell0 W0rld
Split words: ["apple", "banana", "orange"]
Capture groups: year=2024, month=01
/pattern/ or new RegExp("pattern")pattern.test(string) → true/falsestring.match(pattern) → array or nullstring.replace(pattern, replacement)\d (digit), \w (word), \s (space)/(\d+)-(\d+)/ → match[1], match[2]Review feedback below
// 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);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 millisecondsconst 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:00const 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"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"); // 14const 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);Date.now() for current timestamp (faster than new Date().getTime())Current date: Mon Jan 15 2024
Year: 2024, Month: 0, Day: 15
Formatted: January 15, 2024
Tomorrow: Tue Jan 16 2024
Days between: 14
new Date(), new Date("2024-01-15")getFullYear(), getMonth(), getDate()setFullYear(), setMonth(), setDate()toDateString(), toLocaleDateString()date.setDate(date.getDate() + n)Date.now(), date.getTime()Review feedback below
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]); // 1JSON.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"
}
*/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); // 2const 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 emailconst 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()); // 2024function 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)JSON.stringify(obj, null, 2) for readable outputJSON.parse() in try/catchParsed: { 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
JSON.parse(jsonString)JSON.stringify(object)JSON.stringify(obj, null, 2)JSON.stringify(obj, replacerFn)JSON.parse(str, reviverFn)try { } catch { }Review feedback below