Assignments Of Day 26: Regular Expressions in JavaScript
Assignment
1: Validate Email Address
Problem: Write a
regular expression to validate email addresses. An email is valid if it
contains:
- One
"@" symbol.
- At
least one character before and after the "@" symbol.
- A
period (.) after the "@" symbol, followed by the domain (e.g., example.com).
Write a JavaScript function that
checks if a given email is valid.
Solution:
javascript
Copy code
function validateEmail(email)
{
var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
return regex.test(email);
}
console.log(validateEmail('test@example.com'));
// true
console.log(validateEmail('invalid-email')); // false
console.log(validateEmail('name@domain.co')); // true
console.log(validateEmail('name@domain.123')); // false
Assignment
2: Extract All Words with 3 Letters
Problem: Write a
regular expression to extract all the words that contain exactly 3 letters from
a given sentence.
Solution:
javascript
Copy code
function extractThreeLetterWords(sentence)
{
var regex = /\b[a-zA-Z]{3}\b/g;
return sentence.match(regex);
}
console.log(extractThreeLetterWords('The
cat ran fast and hit the mat.')); // ["cat", "ran",
"and", "hit", "the"]
Assignment
3: Find All Dates (DD/MM/YYYY)
Problem: Write a
regular expression that matches dates in the format DD/MM/YYYY (e.g., 25/12/2024).
Solution:
javascript
Copy code
function findDates(str)
{
var regex = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/g;
return str.match(regex);
}
console.log(findDates('25/12/2024
13/03/2023')); // ["25/12/2024", "13/03/2023"]
console.log(findDates('2024-12-25
2023-03-13')); // null
Assignment
4: Replace Multiple Spaces with a Single Space
Problem: Write a
JavaScript function that replaces multiple consecutive spaces with a single
space in a given string.
Solution:
javascript
Copy code
function replaceMultipleSpaces(str)
{
var regex = /\s+/g;
return str.replace(regex, ' ');
}
console.log(replaceMultipleSpaces('This is
a test.')); // "This is a
test."
Assignment
5: Match All Phone Numbers (XXX-XXX-XXXX)
Problem: Write a
regular expression to match phone numbers in the format XXX-XXX-XXXX where X is
a digit (0-9).
Solution:
javascript
Copy code
function matchPhoneNumber(str)
{
var regex = /\d{3}-\d{3}-\d{4}/g;
return str.match(regex);
}
console.log(matchPhoneNumber('Call
me at 123-456-7890 or 987-654-3210.')); // ["123-456-7890",
"987-654-3210"]
console.log(matchPhoneNumber('No
phone number here!')); // null
Assignment
6: Extract All Hashtags from a Text
Problem: Write a
regular expression to extract all hashtags (words starting with #), e.g., #hello,
#world.
Solution:
javascript
Copy code
function extractHashtags(text)
{
var regex = /#\w+/g;
return text.match(regex);
}
console.log(extractHashtags('I
love #JavaScript and #coding!')); // ["#JavaScript",
"#coding"]
console.log(extractHashtags('No
hashtags here!')); // null
Assignment
7: Remove All Non-Alphanumeric Characters
Problem: Write a
function that removes all characters that are not letters or numbers from a
given string.
Solution:
javascript
Copy code
function removeNonAlphanumeric(str)
{
var regex = /[^a-zA-Z0-9]/g;
return str.replace(regex, '');
}
console.log(removeNonAlphanumeric('Hello!
How are you?')); // "HelloHowareyou"
Assignment
8: Validate US Zip Code
Problem: Write a
regular expression to validate a US ZIP code. A valid ZIP code should:
- Be 5
digits long (e.g., 12345).
- Optionally,
include a hyphen and 4 additional digits (e.g., 12345-6789).
Solution:
javascript
Copy code
function validateZipCode(zip)
{
var regex = /^\d{5}(-\d{4})?$/;
return regex.test(zip);
}
console.log(validateZipCode('12345')); // true
console.log(validateZipCode('12345-6789')); // true
console.log(validateZipCode('1234')); // false
console.log(validateZipCode('12345-678')); // false
Assignment
9: Validate Strong Password
Problem: Write a
regular expression to validate strong passwords. A strong password must:
- Be
at least 8 characters long.
- Contain
at least one lowercase letter, one uppercase letter, one digit, and one
special character.
Solution:
javascript
Copy code
function validatePassword(password)
{
var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/;
return regex.test(password);
}
console.log(validatePassword('Strong@123'));
// true
console.log(validatePassword('weak123')); // false
Assignment
10: Find All Words Starting with a Vowel
Problem: Write a
function that returns all words in a given sentence that start with a vowel (a,
e, i, o, u).
Solution:
javascript
Copy code
function findWordsStartingWithVowel(sentence)
{
var regex = /\b[aeiouAEIOU]\w*/g;
return sentence.match(regex);
}
console.log(findWordsStartingWithVowel('An
apple is on the island.')); // ["An", "apple",
"is", "island"]
Conclusion:
These assignments cover various
practical uses of regular expressions in JavaScript. By solving these, you will
get a strong grasp of how to:
- Validate
data like email addresses, zip codes, and passwords.
- Extract
meaningful data from strings, such as dates, phone numbers, and hashtags.
- Manipulate
strings by replacing or removing specific patterns.
Understanding regular expressions
will significantly enhance your ability to work with strings and handle user
input in your JavaScript applications.
4o mini
You said:
give more
ChatGPT
said:
ChatGPT
Here are more assignments based
on Regular Expressions in JavaScript:
Assignment
11: Validate IPv4 Address
Problem: Write a
regular expression to validate an IPv4 address. A valid IPv4 address should
consist of four sets of digits between 0 and 255, separated by periods.
Solution:
javascript
Copy code
function validateIPv4(ip)
{
var regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return regex.test(ip);
}
console.log(validateIPv4('192.168.1.1')); // true
console.log(validateIPv4('256.256.256.256'));
// false
console.log(validateIPv4('127.0.0.1')); // true
Assignment
12: Validate Hexadecimal Color Code
Problem: Write a
regular expression to validate hexadecimal color codes. A valid hex code starts
with # and is followed by six hexadecimal characters (0-9, A-F).
Solution:
javascript
Copy code
function validateHexColor(color)
{
var regex = /^#([0-9A-Fa-f]{6})$/;
return regex.test(color);
}
console.log(validateHexColor('#A3C1F7')); // true
console.log(validateHexColor('#123ABC')); // true
console.log(validateHexColor('123456')); // false
Assignment
13: Extract All Numbers from a String
Problem: Write a
regular expression to extract all numbers from a given string.
Solution:
javascript
Copy code
function extractNumbers(str)
{
var regex = /\d+/g;
return str.match(regex);
}
console.log(extractNumbers('There
are 12 apples and 4 bananas.')); // ["12", "4"]
console.log(extractNumbers('No
numbers here!')); //
null
Assignment
14: Extract All Links from HTML
Problem: Write a
regular expression to extract all the links (URLs) from an HTML string.
Solution:
javascript
Copy code
function extractLinks(html)
{
var regex = /href="([^"]*)"/g;
var matches;
var links = [];
while ((matches = regex.exec(html)) !== null)
{
links.push(matches[1]);
}
return links;
}
var
htmlString = '<a href="https://www.example.com">Link
1</a><a href="https://www.test.com">Link 2</a>';
console.log(extractLinks(htmlString));
// ["https://www.example.com", "https://www.test.com"]
Assignment
15: Match Only Alphabetical Words
Problem: Write a
regular expression to find words that contain only letters (i.e., no numbers or
special characters).
Solution:
javascript
Copy code
function matchAlphaWords(str)
{
var regex = /\b[a-zA-Z]+\b/g;
return str.match(regex);
}
console.log(matchAlphaWords('Hello
World 123! This is a test.')); // ["Hello", "World",
"This", "is", "a", "test"]
Assignment
16: Replace Multiple Dashes with One
Problem: Write a
function that replaces all occurrences of multiple consecutive dashes (--) with
a single dash (-).
Solution:
javascript
Copy code
function replaceMultipleDashes(str)
{
var regex = /-+/g;
return str.replace(regex, '-');
}
console.log(replaceMultipleDashes('This
-- is --- a ---test--case')); // "This - is - a -test-case"
Assignment
17: Match Only Uppercase Words
Problem: Write a
regular expression to match only words that are entirely uppercase.
Solution:
javascript
Copy code
function matchUppercaseWords(str)
{
var regex = /\b[A-Z]+\b/g;
return str.match(regex);
}
console.log(matchUppercaseWords('This
is a TEST message with HELLO and WORLD.')); // ["TEST",
"HELLO", "WORLD"]
Assignment
18: Extract All Dates (MM-DD-YYYY)
Problem: Write a
regular expression to match dates in the format MM-DD-YYYY (e.g., 12-31-2024).
Solution:
javascript
Copy code
function findDatesMMDDYYYY(str)
{
var regex = /\b(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-\d{4}\b/g;
return str.match(regex);
}
console.log(findDatesMMDDYYYY('Today
is 12-31-2024 and tomorrow is 01-01-2025.'));
console.log(findDatesMMDDYYYY('Invalid
dates like 32-01-2024 are not matched.'));
Assignment
19: Validate Phone Number (With or Without Hyphen)
Problem: Write a
regular expression that validates a phone number in the format XXX-XXX-XXXX or XXXXXXXXXX
(e.g., 123-456-7890 or 1234567890).
Solution:
javascript
Copy code
function validatePhoneNumber(phone)
{
var regex = /^(?:\d{3}-\d{3}-\d{4}|\d{10})$/;
return regex.test(phone);
}
console.log(validatePhoneNumber('123-456-7890')); // true
console.log(validatePhoneNumber('1234567890')); // true
console.log(validatePhoneNumber('12345-67890')); // false
Assignment
20: Validate Username (Alphanumeric, 5-10 Characters)
Problem: Write a
regular expression to validate a username. The username should:
- Be
5-10 characters long.
- Contain
only letters and numbers.
Solution:
javascript
Copy code
function validateUsername(username)
{
var regex = /^[a-zA-Z0-9]{5,10}$/;
return regex.test(username);
}
console.log(validateUsername('user123')); // true
console.log(validateUsername('12345abc')); // true
console.log(validateUsername('user@123')); // false
console.log(validateUsername('usr')); // false
Assignment
21: Extract All Words with Digits
Problem: Write a
regular expression to find all words that contain digits in a given string.
Solution:
javascript
Copy code
function extractWordsWithDigits(str)
{
var regex = /\b\w*\d\w*\b/g;
return str.match(regex);
}
console.log(extractWordsWithDigits('There
are 100 apples, 200 bananas, and 3 oranges.')); // ["100",
"200", "3"]
Assignment
22: Remove Leading and Trailing Spaces
Problem: Write a
function to remove any leading or trailing spaces from a string using regular
expressions.
Solution:
javascript
Copy code
function trimSpaces(str)
{
var regex = /^\s+|\s+$/g;
return str.replace(regex, '');
}
console.log(trimSpaces(' Hello World!
')); // "Hello World!"
Assignment
23: Validate Credit Card Number
Problem: Write a
regular expression to validate a credit card number in the format ####-####-####-####.
Solution:
javascript
Copy code
function validateCreditCard(cardNumber)
{
var regex = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
return regex.test(cardNumber);
}
console.log(validateCreditCard('1234-5678-9012-3456'));
// true
console.log(validateCreditCard('12345-6789-0123-4567'));
// false
Assignment
24: Match Only Lowercase Words
Problem: Write a
regular expression to find words that are entirely lowercase.
Solution:
javascript
Copy code
function matchLowercaseWords(str)
{
var regex = /\b[a-z]+\b/g;
return str.match(regex);
}
console.log(matchLowercaseWords('This
is a test with lowercase words like apple and ball.'));
Assignment
25: Match Any Word Starting with a Vowel
Problem: Write a
regular expression that matches any word in a string that starts with a vowel
(a, e, i, o, u).
Solution:
javascript
Copy code
function matchVowelStartWords(str)
{
var regex = /\b[aeiouAEIOU]\w*/g;
return str.match(regex);
}
console.log(matchVowelStartWords('An
apple is on an island.')); // ["An", "apple",
"is", "on", "an"]
Conclusion
These assignments will help
students practice using regular expressions to solve real-world problems like
validating input, manipulating strings, and extracting relevant data from text.
Regular expressions are a powerful tool in JavaScript for working with text and
validating user inputs efficiently.
