Regular expressions, often referred to as regex or regexp, are powerful patterns used for matching character combinations in strings. In JavaScript, regular expressions are represented by the RegExp object. They provide a concise and flexible way to search, match, and manipulate text.
Basics of Regular Expressions:
Creating a Regular Expression:
Regular expressions can be created using a literal notation or the RegExp constructor.
// Literal notation
let regexLiteral = /pattern/;
// Using RegExp constructor
let regexConstructor = new RegExp(“pattern”);
Metacharacters:
Regular expressions consist of ordinary characters (like letters and numbers) and metacharacters that have special meaning. Some common metacharacters include . (any character), ^ (start of a line), $ (end of a line), * (zero or more occurrences), + (one or more occurrences), and ? (zero or one occurrence).
let pattern = /ab*c/;
Regular Expression Methods:
test():
The test() method checks if a pattern exists in a string and returns true or false.
let regex = /world/;
let result = regex.test(“Hello, world!”); // true
exec():
The exec() method searches for a match in a string. It returns an array containing the matched text and additional information or null if no match is found.
let regex = /world/;
let result = regex.exec(“Hello, world!”); // [“world”, index: 7, input: “Hello, world!”, groups: undefined]
Character Classes:
[] – Character Set:
A character set allows you to match any one of a set of characters.
let regex = /[aeiou]/;
[^] – Negated Character Set:
Match any character that is not in the specified set.
let regex = /[^0-9]/;
Quantifiers:
{n}:
Matches exactly n occurrences of the preceding character or group.
let regex = /a{3}/;
{n,}:
Matches n or more occurrences of the preceding character or group.
let regex = /\d{2,}/; // Match two or more digits
{n,m}:
Matches between n and m occurrences of the preceding character or group.
let regex = /\w{2,4}/; // Match between 2 and 4 word characters
Examples:
Matching Email Addresses:
let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
let isValidEmail = emailRegex.test(“user@example.com”);
Extracting Dates from Text:
let dateRegex = /\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/;
let dateString = “Today’s date is 12/25/2023.”;
let dateMatch = dateString.match(dateRegex);
Replacing Text:
let text = “Hello, my name is John.”;
let nameRegex = /John/;
let updatedText = text.replace(nameRegex, “Doe”);
Regular expressions can be intricate, and mastering them takes practice. Use online tools to test and visualize your patterns, and gradually explore more advanced features to handle diverse scenarios.
Advanced Regular Expression Features:
Grouping ( ):
Parentheses are used for grouping parts of a pattern together.
let regex = /(ab)+/;
Capturing Groups ( ):
Capturing groups allow you to extract matched parts of a pattern.
let dateRegex = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
let dateString = “Today’s date is 12/25/2023.”;
let dateMatch = dateString.match(dateRegex);
// dateMatch: [“12/25/2023”, “12”, “25”, “2023”]
Non-capturing Groups (?: ):
Non-capturing groups group expressions without capturing the matched result.
let regex = /(?:ab)+/;
Assertions:
Assertions are conditions that must be true for a match to occur.
Positive Lookahead (?= ):
let regex = /Java(?=Script)/;
Negative Lookahead (?! ):
let regex = /Java(?!Script)/;
Quantifiers and Lazy Matching:
Quantifiers (*, +, ?, {n}, {n,}, {n,m}) can be modified with ? to perform lazy (non-greedy) matching.
let greedyRegex = /”.+”/;
let lazyRegex = /”.+?”/;
Examples:
Validating URLs:
Check if a string is a valid URL.
let urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/;
let isValidURL = urlRegex.test(“https://www.example.com”);
Extracting HTML Tags:
Extract all HTML tags from a string.
let htmlRegex = /<[^>]*>/g;
let htmlString = ‘<div>Hello</div><p>World</p>’;
let tags = htmlString.match(htmlRegex);
Validating Passwords:
Ensure a password meets specific criteria.
let passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;
let isValidPassword = passwordRegex.test(“Passw0rd”);
Parsing CSV:
Extract values from a comma-separated values string.
let csvString = “John,Doe,30\nAlice,Smith,25”;
let csvRegex = /([^,\n]+)(,|$)/g;
let csvMatches = […csvString.matchAll(csvRegex)];
// csvMatches: [[“John”, “,”], [“Doe”, “,”], [“30”, “\n”], [“Alice”, “,”], [“Smith”, “,”], [“25”, “”]]
Replacing Words with Callback:
Use a callback function with replace to modify matched substrings.
let text = “Hello world, this is awesome.”;
let regex = /\b(\w+)\b/g;
let updatedText = text.replace(regex, (match, word) => word.toUpperCase());
// updatedText: “HELLO WORLD, THIS IS AWESOME.”
Understanding regular expressions is a powerful skill that can greatly enhance your ability to manipulate and validate strings in JavaScript. Practice with different patterns and scenarios to solidify your understanding.
Coding Exercise Regex
Exercise 1: Validate Email Address
Description: Create a function that validates whether a given string is a valid email address.
Steps:
- Define a regular expression for validating email addresses.
- Write a function that uses the regular expression to check if the input is a valid email address.
Code Example:
function isValidEmail(email) {
// Regular expression for email validation
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Test the function
console.log(isValidEmail(“user@example.com”)); // true
console.log(isValidEmail(“invalid-email”)); // false
Solution:
function isValidEmail(email) {
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
Exercise 2: Extract Numbers from String
Description: Write a function that extracts all the numbers from a given string.
Steps:
- Define a regular expression to match numbers.
- Write a function that uses match to extract all numbers from the input string.
Code Example:
function extractNumbers(inputString) {
// Regular expression to match numbers
let numberRegex = /\d+/g;
return inputString.match(numberRegex);
}
// Test the function
console.log(extractNumbers(“The price is $20 and the quantity is 5.”)); // [’20’, ‘5’]
Solution:
function extractNumbers(inputString) {
let numberRegex = /\d+/g;
return inputString.match(numberRegex);
}
Exercise 3: Replace HTML Tags
Description: Create a function that replaces all HTML tags in a given string with an empty string.
Steps:
- Define a regular expression to match HTML tags.
- Write a function that uses replace to remove all HTML tags.
Code Example:
function removeHtmlTags(inputString) {
// Regular expression to match HTML tags
let htmlTagRegex = /<[^>]*>/g;
return inputString.replace(htmlTagRegex, ”);
}
// Test the function
console.log(removeHtmlTags(“<p>Hello</p><div>World</div>”)); // ‘HelloWorld’
Solution:
function removeHtmlTags(inputString) {
let htmlTagRegex = /<[^>]*>/g;
return inputString.replace(htmlTagRegex, ”);
}
Exercise 4: Validate Password Strength
Description: Write a function that checks whether a given password meets certain criteria.
Steps:
- Define a regular expression to enforce password criteria.
- Write a function that uses the regular expression to validate the password.
Code Example:
function isValidPassword(password) {
// Regular expression for password validation
let passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;
return passwordRegex.test(password);
}
// Test the function
console.log(isValidPassword(“Passw0rd”)); // true
console.log(isValidPassword(“weakpass”)); // false
Solution:
function isValidPassword(password) {
let passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;
return passwordRegex.test(password);
}
Exercise 5: Extract Domain from URL
Description: Write a function that extracts the domain (excluding protocol and path) from a given URL.
Steps:
- Define a regular expression to match the domain part of a URL.
- Write a function that uses match to extract the domain.
Code Example:
function extractDomain(url) {
// Regular expression to match domain part of a URL
let domainRegex = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/;
let match = url.match(domainRegex);
return match ? match[1] : null;
}
// Test the function
console.log(extractDomain(“https://www.example.com/path/to/page”)); // ‘example.com’
Solution:
function extractDomain(url) {
let domainRegex = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/;
let match = url.match(domainRegex);
return match ? match[1] : null;
}
Exercise 6: Validate Date Format
Description: Create a function that validates whether a given string represents a date in the format “MM/DD/YYYY”.
Steps:
- Define a regular expression for validating the date format.
- Write a function that uses the regular expression to check if the input is a valid date.
Code Example:
function isValidDateFormat(dateString) {
// Regular expression for MM/DD/YYYY format
let dateFormatRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;
return dateFormatRegex.test(dateString);
}
// Test the function
console.log(isValidDateFormat(“12/25/2023”)); // true
console.log(isValidDateFormat(“31/12/2023”)); // false
Solution:
function isValidDateFormat(dateString) {
let dateFormatRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;
return dateFormatRegex.test(dateString);
}
Exercise 7: Extract Hashtags from Text
Description: Write a function that extracts all hashtags from a given text.
Steps:
- Define a regular expression to match hashtags.
- Write a function that uses match to extract all hashtags from the input text.
Code Example:
function extractHashtags(text) {
// Regular expression to match hashtags
let hashtagRegex = /\B#\w+/g;
return text.match(hashtagRegex);
}
// Test the function
console.log(extractHashtags(“Check out this #awesome post! #coding #javascript”)); // [‘#awesome’, ‘#coding’, ‘#javascript’]
Solution:
function extractHashtags(text) {
let hashtagRegex = /\B#\w+/g;
return text.match(hashtagRegex);
}
Exercise 8: Validate Credit Card Number
Description: Create a function that validates whether a given string represents a valid credit card number.
Steps:
- Define a regular expression for validating credit card numbers.
- Write a function that uses the regular expression to check if the input is a valid credit card number.
Code Example:
function isValidCreditCardNumber(cardNumber) {
// Regular expression for credit card validation (simple example)
let creditCardRegex = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
return creditCardRegex.test(cardNumber);
}
// Test the function
console.log(isValidCreditCardNumber(“1234-5678-9012-3456”)); // true
console.log(isValidCreditCardNumber(“invalid-card-number”)); // false
Solution:
function isValidCreditCardNumber(cardNumber) {
let creditCardRegex = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
return creditCardRegex.test(cardNumber);
}
Exercise 9: Replace URLs with Links
Description: Write a function that replaces all URLs in a given text with clickable links.
Steps:
- Define a regular expression to match URLs.
- Write a function that uses replace to replace URLs with HTML links.
Code Example:
function replaceUrlsWithLinks(text) {
// Regular expression to match URLs
let urlRegex = /https?:\/\/\S+/g;
return text.replace(urlRegex, (url) => `<a href=”${url}” target=”_blank”>${url}</a>`);
}
// Test the function
console.log(replaceUrlsWithLinks(“Check out https://www.example.com and https://github.com!”));
// ‘Check out <a href=”https://www.example.com” target=”_blank”>https://www.example.com</a> and <a href=”https://github.com” target=”_blank”>https://github.com</a>!’
Solution:
function replaceUrlsWithLinks(text) {
let urlRegex = /https?:\/\/\S+/g;
return text.replace(urlRegex, (url) => `<a href=”${url}” target=”_blank”>${url}</a>`);
}
Exercise 10: Validate Phone Number
Description: Create a function that validates whether a given string represents a valid phone number.
Steps:
- Define a regular expression for validating phone numbers.
- Write a function that uses the regular expression to check if the input is a valid phone number.
Code Example:
function isValidPhoneNumber(phoneNumber) {
// Regular expression for phone number validation (simple example)
let phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
return phoneRegex.test(phoneNumber);
}
// Test the function
console.log(isValidPhoneNumber(“123-456-7890”)); // true
console.log(isValidPhoneNumber(“invalid-phone-number”)); // false
Solution:
function isValidPhoneNumber(phoneNumber) {
let phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
return phoneRegex.test(phoneNumber);
}
These exercises cover a range of scenarios where regular expressions can be applied. Feel free to customize them or create additional exercises to further enhance your understanding of regular expressions in JavaScript.
Regex Quiz Questions
Quiz Questions:
- Question: What is a regular expression in JavaScript?
- Question: Which object in JavaScript is used for working with regular expressions?
- Question: What does the test() method of a RegExp object do?
- Question: Which character is used as the delimiter for a regular expression literal?
- Question: What does the exec() method of a RegExp object return?
- Question: Which quantifier matches zero or more occurrences of the preceding element?
- Question: What is the purpose of the ^ anchor in a regular expression?
- Question: Which character class matches any digit character?
- Question: In the regular expression /ab+c/, what does the + symbol represent?
- Question: What is the purpose of the non-capturing group (?: ) in a regular expression?
- Question: What does the ? quantifier indicate in a regular expression?
- Question: Which assertion checks if a certain element is followed by another element without including the latter in the match?
- Question: What is the purpose of the g flag in a regular expression?
- Question: Which character is used for matching any character except a newline?
- Question: In the regular expression /[aeiou]/, what does the character class [aeiou] represent?
- Question: Which quantifier matches exactly three occurrences of the preceding element?
- Question: What does the replace() method do when used with a regular expression?
- Question: Which method is used to find all occurrences of a pattern in a string, including capturing groups?
- Question: In the regular expression /^[\w.-]+@[a-z]+\.[a-z]+$/i, what does the i flag represent?
- Question: What is the purpose of the \b anchor in a regular expression?
- Question: Which method returns an array of all occurrences of a pattern in a string without capturing groups?
- Question: In the regular expression /[^0-9]/, what does the character class [^0-9] represent?
- Question: Which quantifier matches between two and four occurrences of the preceding element?
- Question: What does the \d character class represent in a regular expression?
- Question: In the regular expression /^\d{3}-\d{2}-\d{4}$/, what does the pattern represent?
- Question: What does the matchAll() method return?
- Question: What does the \S character class represent in a regular expression?
- Question: In the regular expression /(\w+)\s(\w+)/, what do the capturing groups (\w+) represent?
- Question: Which character is used to escape a metacharacter in a regular expression?
- Question: What is the purpose of the search() method in JavaScript when used with a regular expression?
- Question: Which method splits a string into an array of substrings based on a regular expression?
- Question: What is the purpose of the \w character class in a regular expression?
- Question: In the regular expression /(\d{2})\/(\d{2})\/(\d{4})/, what do the capturing groups (\d{2}), (\d{2}), and (\d{4}) represent?
- Question: What is the purpose of the \W character class in a regular expression?
- Question: In the regular expression /(\b\w+\b)\s\1/, what does \1 represent?
- Question: What does the \b anchor do in a regular expression?
- Question: Which quantifier matches one or more occurrences of the preceding element?
- Question: In the regular expression /^[A-Z][a-z]*$/, what does the pattern represent?
- Question: What is the purpose of the \n escape sequence in a regular expression?
- Question: In the regular expression /(\d+)\s(?:years?|yrs?)/, what does (?:years?|yrs?) represent?
- Question: What is the purpose of the \s character class in a regular expression?
- Question: In the regular expression /(\d{3})-(\d{2})-(\d{4})/, what does the capturing group (\d{3}) represent?
- Question: Which method is used to test if a string contains a pattern in a regular expression?
- Question: What does the \S+ pattern represent in a regular expression?
- Question: In the regular expression /^[a-zA-Z]\w*$/, what does the pattern represent?
- Question: What is the purpose of the \ character in a regular expression?
- Question: In the regular expression /[^aeiou]/, what does the character class [^aeiou] represent?
- Question: What does the flags property of a RegExp object return?
- Question: What is the purpose of the $ anchor in a regular expression?
- Question: In the regular expression /([a-z]+)\s(\d+)/, what do the capturing groups ([a-z]+) and (\d+) represent?
Question: What is a regular expression in JavaScript?
A) A string
B) A data type
C) A pattern describing a certain amount of text
Question: Which object in JavaScript is used for working with regular expressions?
A) RegexObject
B) String
C) RegExp
Question: What does the test() method of a RegExp object do?
A) Returns a new regular expression
B) Tests a string for a match against a regular expression
C) Replaces text in a string with a specified value
Question: Which character is used as the delimiter for a regular expression literal?
A) /
B) |
C) #
Question: What does the exec() method of a RegExp object return?
A) An array containing matched text
B) The matched text
C) null if no match is found
Question: Which quantifier matches zero or more occurrences of the preceding element?
A) +
B) *
C) ?
Question: What is the purpose of the ^ anchor in a regular expression?
A) Matches the end of a string
B) Matches the start of a string
C) Matches any character
Question: Which character class matches any digit character?
A) \d
B) \w
C) \s
Question: In the regular expression /ab+c/, what does the + symbol represent?
A) Matches the character “a”
B) Matches the character “b”
C) Matches one or more occurrences of the character “b”
Question: What is the purpose of the non-capturing group (?: ) in a regular expression?
A) Captures the matched text
B) Creates a capturing group
C) Groups expressions without capturing the matched result
Question: What does the ? quantifier indicate in a regular expression?
A) Matches zero or one occurrence of the preceding element
B) Matches one or more occurrences of the preceding element
C) Matches any character
Question: Which assertion checks if a certain element is followed by another element without including the latter in the match?
A) Positive Lookahead (?= )
B) Negative Lookahead (?! )
C) Positive Lookbehind (?<= )
Question: What is the purpose of the g flag in a regular expression?
A) Global match (find all matches)
B) Case-insensitive match
C) Multiline match
Question: Which character is used for matching any character except a newline?
A) .
B) \n
C) *
Question: In the regular expression /[aeiou]/, what does the character class [aeiou] represent?
A) Matches any vowel
B) Matches any consonant
C) Matches any digit
Question: Which quantifier matches exactly three occurrences of the preceding element?
A) {3}
B) {3,}
C) {0,3}
Question: What does the replace() method do when used with a regular expression?
A) Removes text from a string
B) Replaces text in a string with a specified value
C) Returns a new string
Question: Which method is used to find all occurrences of a pattern in a string, including capturing groups?
A) exec()
B) test()
C) matchAll()
Question: In the regular expression /^[\w.-]+@[a-z]+\.[a-z]+$/i, what does the i flag represent?
A) Case-sensitive match
B) Global match
C) Case-insensitive match
Question: What is the purpose of the \b anchor in a regular expression?
A) Matches a word boundary
B) Matches the end of a string
C) Matches the start of a string
Question: Which method returns an array of all occurrences of a pattern in a string without capturing groups?
A) exec()
B) match()
C) search()
Question: In the regular expression /[^0-9]/, what does the character class [^0-9] represent?
A) Matches any digit
B) Matches any non-digit
C) Matches any word character
Question: Which quantifier matches between two and four occurrences of the preceding element?
A) {2,4}
B) {2}
C) {4,}
Question: What does the \d character class represent in a regular expression?
A) Matches any digit
B) Matches any non-digit
C) Matches any word character
Question: In the regular expression /^\d{3}-\d{2}-\d{4}$/, what does the pattern represent?
A) Social Security Number (SSN) format
B) Date format
C) Phone number format
Question: What does the matchAll() method return?
A) The first match of a pattern
B) An array of all matches of a pattern, including capturing groups
C) The index of the first occurrence of a pattern
Question: What does the \S character class represent in a regular expression?
A) Matches any whitespace character
B) Matches any non-whitespace character
C) Matches any word character
Question: In the regular expression /(\w+)\s(\w+)/, what do the capturing groups (\w+) represent?
A) Matches any word character
B) Captures the first and last names
C) Creates a non-capturing group
Question: Which character is used to escape a metacharacter in a regular expression?
A) !
B) \
C) |
Question: What is the purpose of the search() method in JavaScript when used with a regular expression?
A) Searches for a pattern in a string and returns the index of the first match
B) Replaces the first occurrence of a pattern in a string
C) Tests a string for a match against a regular expression
Question: Which method splits a string into an array of substrings based on a regular expression?
A) split()
B) slice()
C) splice()
Question: What is the purpose of the \w character class in a regular expression?
A) Matches any whitespace character
B) Matches any word character
C) Matches any non-word character
Question: In the regular expression /(\d{2})\/(\d{2})\/(\d{4})/, what do the capturing groups (\d{2}), (\d{2}), and (\d{4}) represent?
A) Captures the day, month, and year in a date
B) Matches any two digits
C) Creates non-capturing groups
Question: What is the purpose of the \W character class in a regular expression?
A) Matches any whitespace character
B) Matches any non-word character
C) Matches any word character
Question: In the regular expression /(\b\w+\b)\s\1/, what does \1 represent?
A) Matches the same word as captured in the first capturing group
B) Matches any word boundary
C) Creates a non-capturing group
Question: What does the \b anchor do in a regular expression?
A) Matches a word boundary
B) Matches any non-word character
C) Matches any word character
Question: Which quantifier matches one or more occurrences of the preceding element?
A) ?
B) *
C) +
Question: In the regular expression /^[A-Z][a-z]*$/, what does the pattern represent?
A) Matches a sentence
B) Matches a capitalized word
C) Matches an email address
Question: What is the purpose of the \n escape sequence in a regular expression?
A) Matches a newline character
B) Matches a non-word character
C) Matches a word character
Question: In the regular expression /(\d+)\s(?:years?|yrs?)/, what does (?:years?|yrs?) represent?
A) Captures the number of years
B) Creates a non-capturing group for “years” or “yrs”
C) Matches the literal characters “years” or “yrs”
Question: What is the purpose of the \s character class in a regular expression?
A) Matches any whitespace character
B) Matches any non-whitespace character
C) Matches any word character
Question: In the regular expression /(\d{3})-(\d{2})-(\d{4})/, what does the capturing group (\d{3}) represent?
A) Captures the area code in a phone number
B) Matches any three digits
C) Creates a non-capturing group
Question: Which method is used to test if a string contains a pattern in a regular expression?
A) contains()
B) includes()
C) test()
Question: What does the \S+ pattern represent in a regular expression?
A) Matches one or more occurrences of any character
B) Matches one or more occurrences of any non-whitespace character
C) Creates a non-capturing group
Question: In the regular expression /^[a-zA-Z]\w*$/, what does the pattern represent?
A) Matches an email address
B) Matches a variable name in JavaScript
C) Matches a sentence
Question: What is the purpose of the \ character in a regular expression?
A) Represents an escape character
B) Matches any character
C) Creates a non-capturing group
Question: In the regular expression /[^aeiou]/, what does the character class [^aeiou] represent?
A) Matches any vowel
B) Matches any non-vowel
C) Matches any digit
Question: What does the flags property of a RegExp object return?
A) The source pattern of the regular expression
B) The index of the first match
C) A string containing the flags used in the regular expression
Question: What is the purpose of the $ anchor in a regular expression?
A) Matches the end of a string
B) Matches the start of a string
C) Matches any character
Question: In the regular expression /([a-z]+)\s(\d+)/, what do the capturing groups ([a-z]+) and (\d+) represent?
A) Captures a word and a number in a string
B) Matches any lowercase letter and any digit
C) Creates non-capturing groups
Quiz Answers
- Answer: C) A pattern describing a certain amount of text
- Answer: C) RegExp
- Answer: B) Tests a string for a match against a regular expression
- Answer: A) /
- Answer: A) An array containing matched text
- Answer: B) *
- Answer: B) Matches the start of a string
- Answer: A) \d
- Answer: C) Matches one or more occurrences of the character “b”
- Answer: C) Groups expressions without capturing the matched result
- Answer: A) Matches zero or one occurrence of the preceding element
- Answer: B) Negative Lookahead (?! )
- Answer: A) Global match (find all matches)
- Answer: A) .
- Answer: A) Matches any vowel
- Answer: A) {3}
- Answer: B) Replaces text in a string with a specified value
- Answer: C) matchAll()
- Answer: C) Case-insensitive match
- Answer: A) Matches a word boundary
- Answer: B) match()
- Answer: B) Matches any non-digit
- Answer: A) {2,4}
- Answer: A) Matches any digit
- Answer: A) Social Security Number (SSN) format
- Answer: B) An array of all matches of a pattern, including capturing groups
- Answer: B) Matches any non-whitespace character
- Answer: B) Captures the first and last names
- Answer: B) \
- Answer: A) Searches for a pattern in a string and returns the index of the first match
- Answer: A) split()
- Answer: B) Matches any word character
- Answer: A) Captures the day, month, and year in a date
- Answer: B) Matches any non-word character
- Answer: A) Matches the same word as captured in the first capturing group
- Answer: A) Matches a word boundary
- Answer: C) +
- Answer: B) Matches a capitalized word
- Answer: A) Matches a newline character
- Answer: B) Creates a non-capturing group for “years” or “yrs”
- Answer: A) Matches any whitespace character
- Answer: B) Matches any three digits
- Answer: C) test()
- Answer: B) Matches one or more occurrences of any non-whitespace character
- Answer: B) Matches a variable name in JavaScript
- Answer: A) Represents an escape character
- Answer: B) Matches any non-vowel
- Answer: C) A string containing the flags used in the regular expression
- Answer: A) Matches the end of a string
- Answer: A) Captures a word and a number in a string