0% found this document useful (0 votes)
6 views

uppalwebt

The document contains JavaScript functions for various tasks including division with error handling, retrieving date information, validating email formats, and a basic calculator application. Each function includes error handling and specific functionalities such as calculating days until the next occurrence of a weekday or performing arithmetic operations. The calculator is implemented in HTML and JavaScript, allowing for basic operations like addition, subtraction, multiplication, division, square root, and exponentiation.

Uploaded by

Prachi Uppal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

uppalwebt

The document contains JavaScript functions for various tasks including division with error handling, retrieving date information, validating email formats, and a basic calculator application. Each function includes error handling and specific functionalities such as calculating days until the next occurrence of a weekday or performing arithmetic operations. The calculator is implemented in HTML and JavaScript, allowing for basic operations like addition, subtraction, multiplication, division, square root, and exponentiation.

Uploaded by

Prachi Uppal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

PRACHI UPPAL

WEB-TECH
Q1. Write a JavaScript function that accepts two numbers as arguments and divides the first
number by the second. The function should handle the following exceptions:
1. If the second number is zero, throw a custom error message indicating that division
by zero is not allowed.
2. If either of the arguments is not a number, throw a custom error message indicating
that the inputs must be numbers.
3. Ensure that all exceptions are properly caught, and display the appropriate error
message using try...catch.

CODE:-
function divideNumbers(num1, num2) {
try {
if (typeof num1 !== 'number' || typeof num2 !==
'number') {
throw new Error("Both inputs must be numbers.");
}
if (num2 === 0) {
throw new Error("Division by zero is not
allowed.");
}
let result = num1 / num2;
return result;
} catch (error) {
return error.message;
}
}

console.log(divideNumbers(10, 2));
console.log(divideNumbers(10, 0));
console.log(divideNumbers(10, 'a'));
Q2. Write a JavaScript function that accepts a date string in the format YYYY-MM-DD (e.g.,
"2024-11-07") and returns the following:
1. The day of the week (e.g., "Monday", "Tuesday", etc.).
2. The number of days remaining until the next occurrence of the same weekday.
3. Whether the given date is in a leap year or not

function getDateInfo(dateString) {
try {
const date = new Date(dateString);

if (isNaN(date)) {
throw new Error("Invalid date format. Please use
YYYY-MM-DD.");
}
const daysOfWeek = ["Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
const currentDay = date.getDay();
const currentDayName = daysOfWeek[currentDay];

const today = new Date();


const nextOccurrenceDate = new Date(date);

nextOccurrenceDate.setFullYear(today.getFullYear());

if (nextOccurrenceDate <= today) {

nextOccurrenceDate.setFullYear(today.getFullYear() + 1);
}

const daysRemaining =
Math.floor((nextOccurrenceDate - today) / (1000 * 60 *
60 * 24));
const year = date.getFullYear();
const isLeapYear = (year % 4 === 0 && (year % 100 !
== 0 || year % 400 === 0));

return {
dayOfWeek: currentDayName,
daysUntilNextOccurrence: daysRemaining,
isLeapYear: isLeapYear
};
} catch (error) {
return error.message;
}
}

console.log(getDateInfo("2024-11-07"));
Q3. Write a JavaScript function that validates and extracts information from a given email
address.(use regex) The function should:
1. Validate if the email address is in a correct format. The format should include:
o A non-empty username (consisting of letters, numbers, or periods).
o The "@" symbol.
o A valid domain name (letters, numbers, or hyphens).
o A period (.) followed by a valid domain extension (like .com, .org, .net).
function validateAndExtractEmail(email) {
const emailRegex = /^[a-zA-Z0-9.]+@[a-zA-Z0-9.-]+\.[a-
zA-Z]{2,6}$/;

if (!emailRegex.test(email)) {
return "Invalid email format.";
}

const regexPattern = /^([a-zA-Z0-9.]+)@([a-zA-Z0-9.-]


+)\.([a-zA-Z]{2,6})$/;
const match = email.match(regexPattern);

if (match) {
const username = match[1];
const domainName = match[2];
const domainExtension = match[3];

return {
username: username,
domainName: domainName,
domainExtension: domainExtension
};
}

return "Email parsing failed.";


}

console.log(validateAndExtractEmail("test.email@examp
le.com"));
console.log(validateAndExtractEmail("invalid-
email.com"));
Q 4. Build a basic calculator application(HTML+JS) that performs the following functions:
 Addition
 Subtraction
 Multiplication
 Division
 Square Root
 Exponentiation (Power)
 Clear (reset the display)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Basic Calculator</title>
<style>
#calculator {
width: 200px;
margin: 0 auto;
padding: 10px;
border: 1px solid #ccc;
border-radius: 10px;
}
input, button {
width: 40px;
height: 40px;
font-size: 18px;
margin: 5px;
}
#display {
width: 180px;
height: 40px;
font-size: 20px;
text-align: right;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="display" disabled>
<br>
<button onclick="appendNumber('7')">7</button>
<button onclick="appendNumber('8')">8</button>
<button onclick="appendNumber('9')">9</button>
<button onclick="operate('+')">+</button>
<br>
<button onclick="appendNumber('4')">4</button>
<button onclick="appendNumber('5')">5</button>
<button onclick="appendNumber('6')">6</button>
<button onclick="operate('-')">-</button>
<br>
<button onclick="appendNumber('1')">1</button>
<button onclick="appendNumber('2')">2</button>
<button onclick="appendNumber('3')">3</button>
<button onclick="operate('*')">*</button>
<br>
<button onclick="appendNumber('0')">0</button>
<button onclick="clearDisplay()">C</button>
<button onclick="calculateResult()">=</button>
<button onclick="operate('/')">/</button>
<br>
<button onclick="calculateSquareRoot()">√</button>
<button
onclick="calculateExponentiation()">^</button>
</div>
<script>
let currentInput = '';
let operator = '';
let firstOperand = '';
let secondOperand = '';

function appendNumber(number) {
currentInput += number;
document.getElementById('display').value =
currentInput;
}

function operate(op) {
if (firstOperand === '') {
firstOperand = currentInput;
operator = op;
currentInput = '';
}
}

function calculateResult() {
secondOperand = currentInput;
let result;
if (operator === '+') {
result = parseFloat(firstOperand) +
parseFloat(secondOperand);
} else if (operator === '-') {
result = parseFloat(firstOperand) -
parseFloat(secondOperand);
} else if (operator === '*') {
result = parseFloat(firstOperand) *
parseFloat(secondOperand);
} else if (operator === '/') {
result = parseFloat(firstOperand) /
parseFloat(secondOperand);
}
currentInput = result.toString();
document.getElementById('display').value =
currentInput;
firstOperand = '';
operator = '';
}

function calculateSquareRoot() {
currentInput =
Math.sqrt(parseFloat(currentInput)).toString();
document.getElementById('display').value =
currentInput;
}

function calculateExponentiation() {
let base = parseFloat(firstOperand);
let exponent = parseFloat(currentInput);
currentInput = Math.pow(base,
exponent).toString();
document.getElementById('display').value =
currentInput;
firstOperand = '';
}

function clearDisplay() {
currentInput = '';
firstOperand = '';
secondOperand = '';
operator = '';
document.getElementById('display').value = '';
}
</script>
</body>
</html>

You might also like