Complete the code to match a string starting with 'Hello' using template literals.
const greeting = 'Hello, world!'; const match = greeting.[1](/^Hello/); console.log(match);
The match method is used to find matches based on patterns, including template literals with embedded expressions.
Complete the code to extract the name from a greeting using pattern matching with template literals.
const greeting = 'Hello, Alice!'; const pattern = `^Hello, (.+)!$`; const result = greeting.match(new RegExp(pattern)); const name = result.[1](1); console.log(name);
The at(1) method accesses the first captured group from the match result array.
Fix the error in the code to correctly test if a string matches a pattern using template literals.
const input = 'user123'; const pattern = new RegExp(`^user\\d+$`); const isMatch = pattern.[1](input); console.log(isMatch);
The test method of a RegExp returns true or false if the string matches the pattern.
Fill both blanks to create a function that extracts the domain from an email using pattern matching with template literals.
function getDomain(email: string) {
const regex = new RegExp(`@(.+)[1]`);
const match = email.match(regex);
return match.[2](1) || null;
}
console.log(getDomain('user@example.com'));The regex uses $ to match the end of the string. The at(1) method accesses the first captured group which is the domain.
Fill all three blanks to create a function that validates and extracts year, month, and day from a date string using template literal pattern matching.
function parseDate(dateStr: string) {
const regex = new RegExp(`^(\d{ [1] })-(\d{ [2] })-(\d{ [3] })$`);
const match = dateStr.match(regex);
if (!match) return null;
return {
year: match.at(1),
month: match.at(2),
day: match.at(3)
};
}
console.log(parseDate('2023-06-15'));The year has 4 digits, month and day have 2 digits each. The regex captures these groups accordingly.