Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Develop a JavaScript program to Capitalize the first letter of each Word of a sentence (String)

To capitalize the first letter of each word in a sentence using JavaScript:


STEPS
1. Split the sentence into individual words.
2. Capitalize the first letter of each word.
3. Join the words back into a single sentence.

function capitalizeFirstLetterOfEachWord(sentence) {
return sentence.split(' ').map(word => {
if (word.length > 0) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
} else {
return word;
}
}).join(' ');
}
const sentence = "hello world! this is a test.";
const capitalizedSentence = capitalizeFirstLetterOfEachWord(sentence);
console.log(capitalizedSentence);
### Explanation:

1. **split(' ')**: The `split` method splits the sentence into an array of words using a space (`' '`)
as the delimiter.
2. **map(word => {...})**: The `map` method iterates over each word in the array, applying a
function to each word.
3. **word[0].toUpperCase() + word.slice(1).toLowerCase()**: For each word:
- `word[0].toUpperCase()` converts the first character to uppercase.
- `word.slice(1).toLowerCase()` takes the rest of the word (from the second character onward)
and converts it to lowercase. This ensures that if the word was in mixed or all uppercase letters, it
becomes properly formatted.
4. **join(' ')**: The `join` method joins the array of words back into a single string, with a space
(`' '`) between each word.

### Handling Edge Cases:


- **Empty strings**: The function handles empty strings gracefully by checking the length of
each word.
- **Multiple spaces**: The function preserves multiple spaces between words. If you want to
collapse multiple spaces into a single space, you can modify the code to handle that.

This program provides a straightforward approach to capitalize the first letter of each word while
ensuring the rest of the word is in lowercase, which is commonly expected in proper title casing.

Develop a JavaScript program to Check a string starts with 'Java'.


To check if a string starts with the substring "Java" in JavaScript, you can use the `startsWith`
method of the `String` object. This method returns `true` if the string starts with the specified
substring, and `false` otherwise.
function startsWithJava(str) {
return str.startsWith('Java');
}

// Example usage:
const testString1 = "JavaScript is a programming language.";
const testString2 = "I love Java and coffee.";
console.log(startsWithJava(testString1)); // Output: true
console.log(startsWithJava(testString2)); // Output: false

Explanation:
1. **startsWith('Java’) **: The `startsWith` method checks if the string begins with the substring
'Java'. It returns `true` if it does, and `false` otherwise.
Alternative Method:
If you want to support older JavaScript environments where `startsWith` is not available, you can
use the `indexOf` method:

function startsWithJava(str) {
return str.indexOf('Java') === 0;
}
// Example usage:
const testString1 = "JavaScript is a programming language.";
const testString2 = "I love Java and coffee.";
console.log(startsWithJava(testString1)); // Output: true
console.log(startsWithJava(testString2)); // Output: false

Explanation:

1. **indexOf('Java') === 0**: The `indexOf` method returns the position of the first occurrence
of the specified substring. If 'Java' is found at the start of the string, `indexOf` will return `0`. If
'Java' is not found at the start, it will return a different value (typically `-1` if 'Java' is not present
at all).

Both methods are effective, but using `startsWith` is more readable and straightforward for this
specific purpose.
Develop a JavaScript program to display the current day and time.

To display the current day and time in JavaScript, you can use the `Date` object, which provides
various methods to get the current date and time. Below is a JavaScript program that displays the
current day and time:

function displayCurrentDayAndTime() {
const now = new Date();

// Array to get the day names


const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday'];

// Get the current day of the week


const dayName = daysOfWeek[now.getDay()];

// Get the current time components


const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

// Format the time as HH:MM:SS


const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:$
{seconds.toString().padStart(2, '0')}`;

// Display the day and time


console.log(`Today is: ${dayName}`);
console.log(`Current time is: ${timeString}`);
}

// Call the function to display the current day and time


displayCurrentDayAndTime();
```
### Explanation:

1. **new Date()**: Creates a new `Date` object representing the current date and time.
2. **daysOfWeek**: An array holding the names of the days of the week.
3. **now.getDay()**: Returns the day of the week as a number (0 for Sunday, 1 for Monday,
etc.). This number is used to index the `daysOfWeek` array to get the day name.
4. **now.getHours(), now.getMinutes(), now.getSeconds()**: Methods to get the current hour,
minute, and second.
5. **padStart(2, '0')**: Ensures that the time components are always two digits, adding a leading
zero if necessary.
6. **console.log**: Displays the formatted day and time.

### Example Output:

If you run the program on a Wednesday at 15:30:45, the output would be:

```
Today is: Wednesday
Current time is: 15:30:45
```
This program provides a clear and formatted display of the current day and time. You can expand
this by adding it to an HTML page or updating it in real-time using JavaScript's `setInterval`
method for a live clock.

Develop a JavaScript program to reverse a given string

Reversing a string in JavaScript can be done by converting the string into an array, reversing the
array, and then converting the array back into a string. Here's a simple program that achieves
this:

function reverseString(str) {
return str.split('').reverse().join('');
}

// Example usage:
const originalString = "Hello, World!";
const reversedString = reverseString(originalString);
console.log(reversedString); // Output: !dlroW ,olleH
### Explanation:

1. **str.split('')**: The `split` method converts the string into an array of characters. For example,
`"Hello"` becomes `['H', 'e', 'l', 'l', 'o']`.
2. **reverse()**: The `reverse` method reverses the order of elements in the array. For example,
`['H', 'e', 'l', 'l', 'o']` becomes `['o', 'l', 'l', 'e', 'H']`.
3. **join('')**: The `join` method converts the array of characters back into a single string. For
example, `['o', 'l', 'l', 'e', 'H']` becomes `"olleH"`.

### Example:
Here is how you can use the function to reverse different strings:

console.log(reverseString("JavaScript")); // Output: tpircSavaJ


console.log(reverseString("OpenAI")); // Output: IAnepO
console.log(reverseString("12345")); // Output: 54321

This program provides a straightforward approach to reverse any given string using built-in
JavaScript methods.

Develop a JavaScript program to display a message using alert.


To display a message using an alert in JavaScript, you can use the built-in `alert` function. This
function displays a modal dialog box with a specified message and an OK button.

Here's a simple JavaScript program to demonstrate this:

function showAlert(message) {
alert(message);
}

// Example usage:
showAlert("Hello, World!");

### Explanation:
1. **alert(message)**: The `alert` function takes a single argument, which is the message you
want to display in the alert dialog box. When called, it will display a modal dialog with the
provided message and an OK button that the user can click to close the alert.

### Example Usage:

You can use the `showAlert` function to display different messages by passing the desired
message as an argument. Here are some examples:

showAlert("Welcome to our website!");


showAlert("This is a warning message.");
showAlert("Please enter a valid email address.");

### Full Example in HTML:

If you want to integrate this into a full HTML page, you can add a button to trigger the alert
when clicked:

html
<!DOCTYPE html>
<html>
<head>
<title>Alert Example</title>
<script>
function showAlert(message) {
alert(mezssage);
}
</script>
</head>
<body>
<button onclick="showAlert('Hello, World!')">Click Me</button>
</body>
</html>

### Explanation of HTML Example:

1. **<script>**: The JavaScript code is placed within a `<script>` tag in the head section of the
HTML document.
2. **<button onclick="showAlert('Hello, World!')">**: A button is added to the body of the
HTML. When the button is clicked, it calls the `showAlert` function with the message "Hello,
World!".

When you open this HTML file in a web browser and click the button, it will display an alert
dialog with the message "Hello, World!".

Develop a JavaScript program to display a confirm message on a button click.

To display a confirmation message when a button is clicked in JavaScript, you can use the
`confirm` function. This function displays a modal dialog with a specified message, along with
OK and Cancel buttons. It returns `true` if the user clicks OK and `false` if the user clicks
Cancel.

Here’s a simple JavaScript program to demonstrate this functionality:

html
<!DOCTYPE html>
<html>
<head>
<title>Confirm Example</title>
<script>
function showConfirm() {
// Display a confirmation dialog
const userConfirmed = confirm("Are you sure you want to proceed?");

// Handle the user's response


if (userConfirmed) {
alert("User clicked OK.");
} else {
alert("User clicked Cancel.");
}
}
</script>
</head>
<body>
<button onclick="showConfirm()">Click Me</button>
</body>
</html>

### Explanation:

1. **confirm(message)**: The `confirm` function displays a confirmation dialog with the


specified message. It returns `true` if the user clicks OK and `false` if the user clicks Cancel.
2. **const userConfirmed = confirm("Are you sure you want to proceed?")**: This line stores
the result of the `confirm` function in the `userConfirmed` variable.

3. **if (userConfirmed) { ... } else { ... }**: This conditional block handles the user's response. If
the user clicked OK, an alert with the message "User clicked OK." is displayed. If the user
clicked Cancel, an alert with the message "User clicked Cancel." is displayed.

### Example Usage:

When you open this HTML file in a web browser and click the button, it will display a
confirmation dialog with the message "Are you sure you want to proceed?". Based on the user's
response, it will show an alert with either "User clicked OK." or "User clicked Cancel.".

This setup provides a simple way to handle user confirmations in a web page using JavaScript.

Develop a JavaScript program to read value through prompt window and display the value on a
button click.

To create a JavaScript program that reads a value through a prompt window and displays that
value on a button click, you can follow these steps:

1. Create an HTML button that, when clicked, triggers a JavaScript function.


2. Use the `prompt` function to read a value from the user.
3. Display the value in the HTML document.

Here is a simple example demonstrating this:

html
<!DOCTYPE html>
<html>
<head>
<title>Prompt Example</title>
<script>
function showPrompt() {
// Display a prompt dialog to get user input
const userInput = prompt("Please enter your name:");

// Display the entered value on the web page


if (userInput !== null) {
document.getElementById("displayArea").innerText = `You entered: ${userInput}`;
} else {
document.getElementById("displayArea").innerText = "You canceled the prompt.";
}
}
</script>
</head>
<body>
<button onclick="showPrompt()">Click Me</button>
<div id="displayArea"></div>
</body>
</html>

### Explanation:

1. **HTML Structure**:
- `<button onclick="showPrompt()">Click Me</button>`: This button, when clicked, calls the
`showPrompt` function.
- `<div id="displayArea"></div>`: This `div` is used to display the value entered by the user.

2. **JavaScript Function**:
- `prompt("Please enter your name:")`: The `prompt` function displays a dialog box that
prompts the user for input. The input value is stored in the `userInput` variable.
- `document.getElementById("displayArea").innerText = ...`: This line sets the text content of
the `div` with the id `displayArea` to the user's input or a message indicating the user canceled
the prompt.

### Example Usage:

- When the user clicks the "Click Me" button, a prompt dialog appears asking the user to enter
their name.
- If the user enters a name and clicks OK, the entered name is displayed in the `div` with the id
`displayArea`.
- If the user clicks Cancel, a message "You canceled the prompt." is displayed instead.

This approach provides a simple and effective way to interact with users and display their input
on a web page using JavaScript.

Develop a JavaScript program to display (on respective button clicks) multiplication and division
of two numbers. Read values from the textboxes and design two buttons (use DOM)

To create a JavaScript program that displays the result of multiplication and division of two
numbers based on button clicks, follow these steps:

1. Create an HTML form with two text boxes to input the numbers.
2. Create two buttons, one for multiplication and one for division.
3. Use JavaScript to read the values from the text boxes, perform the operations, and display the
results.

Here’s an example implementation:

html
<!DOCTYPE html>
<html>
<head>
<title>Multiplication and Division</title>
<script>
function multiplyNumbers() {
// Get the values from the textboxes
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);

// Check if the inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers.");
return;
}

// Perform multiplication
const result = num1 * num2;

// Display the result


document.getElementById("result").innerText = `Result: ${result}`;
}

function divideNumbers() {
// Get the values from the textboxes
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);

// Check if the inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers.");
return;
}

// Check for division by zero


if (num2 === 0) {
alert("Division by zero is not allowed.");
return;
}

// Perform division
const result = num1 / num2;

// Display the result


document.getElementById("result").innerText = `Result: ${result}`;
}
</script>
</head>
<body>
<h2>Multiplication and Division</h2>
<div>
<label for="number1">Number 1:</label>
<input type="text" id="number1">
</div>
<div>
<label for="number2">Number 2:</label>
<input type="text" id="number2">
</div>
<div>
<button onclick="multiplyNumbers()">Multiply</button>
<button onclick="divideNumbers()">Divide</button>
</div>
<div id="result"></div>
</body>
</html>

### Explanation:

1. **HTML Structure**:
- `<label for="number1">Number 1:</label>`: A label for the first number input.
- `<input type="text" id="number1">`: A text box to input the first number.
- `<label for="number2">Number 2:</label>`: A label for the second number input.
- `<input type="text" id="number2">`: A text box to input the second number.
- `<button onclick="multiplyNumbers()">Multiply</button>`: A button that triggers the
multiplication function when clicked.
- `<button onclick="divideNumbers()">Divide</button>`: A button that triggers the division
function when clicked.
- `<div id="result"></div>`: A div to display the result of the operations.

2. **JavaScript Functions**:
- **multiplyNumbers**:
- Reads the values from the text boxes using `document.getElementById`.
- Parses the values as floats.
- Checks if the inputs are valid numbers using `isNaN`.
- Multiplies the numbers and updates the result div with the multiplication result.
- **divideNumbers**:
- Reads the values from the text boxes using `document.getElementById`.
- Parses the values as floats.
- Checks if the inputs are valid numbers using `isNaN`.
- Checks if the second number is zero to prevent division by zero.
- Divides the numbers and updates the result div with the division result.

This implementation ensures that the user inputs are validated and handles potential errors such
as division by zero. The results of the operations are displayed dynamically in the HTML
document.

Develop a JavaScript program to highlight with red color the HTML links () having class name
“high” (use DOM)
To create a JavaScript program that highlights HTML links (`<a>`) with the class name "high"
by changing their color to red, you can follow these steps:
1. Use JavaScript to select all the links with the class name "high".
2. Change the color of these selected links to red.

Here's an example implementation:

html
<!DOCTYPE html>
<html>
<head>
<title>Highlight Links</title>
<style>
/* Ensure default styles for other links */
a{
color: initial;
}
</style>
</head>
<body>
<h2>Links</h2>
<a href="https://example.com" class="high">High Priority Link 1</a>
<a href="https://example.com">Normal Link 1</a>
<a href="https://example.com" class="high">High Priority Link 2</a>
<a href="https://example.com">Normal Link 2</a>

<script>
function highlightLinks() {
// Select all links with class 'high'
const highLinks = document.querySelectorAll('a.high');

// Change the color of the selected links to red


highLinks.forEach(link => {
link.style.color = 'red';
});
}

// Call the function to highlight the links


highlightLinks();
</script>
</body>
</html>
### Explanation:

1. **HTML Structure**:
- Multiple `<a>` tags with and without the class "high" to demonstrate the functionality.

2. **CSS**:
- A basic style to ensure that other links retain their default color (`color: initial;`).

3. **JavaScript**:
- `document.querySelectorAll('a.high')`: This method selects all `<a>` elements with the class
name "high". It returns a NodeList of matching elements.
- `highLinks.forEach(link => { link.style.color = 'red'; })`: This loop iterates over each element
in the NodeList and sets its `style.color` property to red, effectively highlighting the link.

4. **Function Call**:
- `highlightLinks()`: The function is called immediately to highlight the links when the page
loads.

This example demonstrates how to manipulate the DOM to change the styles of specific
elements dynamically using JavaScript. When the page loads, the links with the class "high" are
highlighted in red.

Develop a JavaScript program to read the content of HTML paragraph and update (on button
click event) with the suitable Text read from the HTML Textbox (Use innerHTML)

To create a JavaScript program that reads the content of an HTML paragraph and updates it with
the text entered into an HTML textbox upon a button click event, you can follow these steps:

1. Create an HTML paragraph and textbox.


2. Create a button to trigger the update.
3. Use JavaScript to handle the button click event and update the paragraph content with the text
from the textbox using the `innerHTML` property.

Here's an example implementation:

html
<!DOCTYPE html>
<html>
<head>
<title>Update Paragraph</title>
</head>
<body>
<h2>Update Paragraph</h2>
<p id="paragraph">This is the initial content of the paragraph.</p>
<input type="text" id="textInput" placeholder="Enter new text">
<button onclick="updateParagraph()">Update</button>

<script>
function updateParagraph() {
// Get the content from the textbox
const newText = document.getElementById('textInput').value;

// Update the paragraph with the new content


document.getElementById('paragraph').innerHTML = newText;
}
</script>
</body>
</html>

### Explanation:

1. **HTML Structure**:
- `<p id="paragraph">`: A paragraph element with the id "paragraph" to be updated.
- `<input type="text" id="textInput">`: A text input element with the id "textInput" for entering
new text.
- `<button onclick="updateParagraph()">`: A button with an `onclick` attribute that triggers the
`updateParagraph` function when clicked.

2. **JavaScript Function** (`updateParagraph`):


- `document.getElementById('textInput').value`: This line retrieves the value of the text input
element.
- `document.getElementById('paragraph').innerHTML = newText;`: This line sets the
innerHTML of the paragraph element to the new text entered into the text input.

### Example Usage:

- Enter new text into the text input.


- Click the "Update" button.
- The paragraph content will be updated with the text entered into the textbox.

This program demonstrates how to dynamically update HTML content based on user input using
JavaScript and the `innerHTML` property.

Develop a JavaScript program to check for an attribute (‘href’ in ) and get its value/display on
the Web page on a button click.

To create a JavaScript program that checks for the `href` attribute in an `<a>` (anchor)
element and displays its value on the web page upon a button click event, you can follow
these steps:

1. Create an HTML anchor element (`<a>`) with an `href` attribute.


2. Create a button to trigger the attribute check and display the value.
3. Use JavaScript to handle the button click event, check for the `href` attribute value, and
display it on the web page.

Here's an example implementation:

html
<!DOCTYPE html>
<html>
<head>
<title>Check href Attribute</title>
</head>
<body>
<h2>Check href Attribute</h2>
<a id="link" href="https://example.com">Example Link</a><br>
<button onclick="checkHrefAttribute()">Check href Attribute</button>
<div id="result"></div>

<script>
function checkHrefAttribute() {
// Get the anchor element
const linkElement = document.getElementById('link');

// Get the value of the href attribute


const hrefValue = linkElement.getAttribute('href');

// Display the href attribute value on the web page


document.getElementById('result').innerText = `The value of href attribute is: $
{hrefValue}`;
}
</script>
</body>
</html>

### Explanation:

1. **HTML Structure**:
- `<a id="link" href="https://example.com">`: An anchor element (`<a>`) with the id
"link" and an `href` attribute.
- `<button onclick="checkHrefAttribute()">`: A button with an `onclick` attribute that
triggers the `checkHrefAttribute` function when clicked.
- `<div id="result"></div>`: A `<div>` element with the id "result" to display the result.

2. **JavaScript Function** (`checkHrefAttribute`):


- `document.getElementById('link')`: This line retrieves the anchor element with the id
"link".
- `linkElement.getAttribute('href')`: This line gets the value of the `href` attribute of the
anchor element.
- `document.getElementById('result').innerText = ...`: This line sets the text content of
the `<div>` element with the id "result" to display the value of the `href` attribute.

### Example Usage:

- Click the "Check href Attribute" button.


- The value of the `href` attribute of the anchor element will be displayed on the web
page.

This program demonstrates how to retrieve and display the value of the `href` attribute of
an anchor element using JavaScript.

Develop a JavaScript program to sort a list of numbers (Use arrays and functions)
Sure, here's a JavaScript program that sorts a list of numbers using arrays and functions:

function sortNumbers(numbers) {
// Use the Array.sort() method to sort the numbers in ascending order
numbers.sort(function(a, b) {
return a - b;
});

// Return the sorted array


return numbers;
}

// Example usage:
const unsortedNumbers = [4, 2, 7, 1, 9, 5];
const sortedNumbers = sortNumbers(unsortedNumbers);
console.log(sortedNumbers); // Output: [1, 2, 4, 5, 7, 9]

### Explanation:

1. **sortNumbers function**:
- It takes an array of numbers as input.
- Uses the `Array.sort()` method to sort the numbers.
- The `sort` method accepts a comparison function as an argument. This function determines
the order of the elements. In this case, it sorts the numbers in ascending order.
- The comparison function `(a, b) => a - b` returns a negative value if `a` should come before
`b`, a positive value if `a` should come after `b`, and zero if they are equal.

2. **Example Usage**:
- An example array of unsorted numbers is provided.
- The `sortNumbers` function is called with the unsorted numbers.
- The sorted array is then logged to the console.

This program sorts a list of numbers in ascending order. You can modify it to sort in descending
order by changing the comparison function accordingly.

Develop a JavaScript program to create a hotel object using object literal syntax having
properties
(name, location, room rate, discount etc), constructors and method (offer-price). Create few
objects to
demonstrate the access of properties and an associated method

Sure! Below is a JavaScript program that creates a hotel object using object literal syntax and
demonstrates the access of properties and an associated method:

// Define a hotel object using object literal syntax


const hotel = {
name: "Grand Hotel",
location: "City Center",
roomRate: 200,
discount: 10,
// Method to calculate the offer price
offerPrice: function() {
const discountedPrice = this.roomRate - (this.roomRate * (this.discount / 100));
return discountedPrice;
}
};

// Accessing properties of the hotel object


console.log("Hotel Name:", hotel.name);
console.log("Location:", hotel.location);
console.log("Room Rate:", hotel.roomRate);
console.log("Discount:", hotel.discount + "%");

// Accessing the offerPrice method and displaying the discounted price


console.log("Offer Price:", hotel.offerPrice());

// Create another hotel object


const anotherHotel = {
name: "Ocean View Hotel",
location: "Beachfront",
roomRate: 250,
discount: 15,
offerPrice: function() {
const discountedPrice = this.roomRate - (this.roomRate * (this.discount / 100));
return discountedPrice;
}
};

// Accessing properties and method of the anotherHotel object


console.log("\nHotel Name:", anotherHotel.name);
console.log("Location:", anotherHotel.location);
console.log("Room Rate:", anotherHotel.roomRate);
console.log("Discount:", anotherHotel.discount + "%");
console.log("Offer Price:", anotherHotel.offerPrice());

### Explanation:

1. **Hotel Object**:
- It's defined using object literal syntax `{}`.
- It has properties like `name`, `location`, `roomRate`, and `discount`.
- It has a method `offerPrice` to calculate the discounted room rate.

2. **Accessing Properties**:
- Properties are accessed using dot notation (e.g., `hotel.name`, `hotel.location`).

3. **Accessing Method**:
- The method `offerPrice` is accessed similarly to properties.
- It's invoked as a function (e.g., `hotel.offerPrice()`).

4. **Creating Another Hotel Object**:


- Another hotel object is created similarly to the first one.
- It has its own set of properties and method.
5. **Displaying Information**:
- Information about each hotel object (name, location, room rate, discount, and offer price) is
displayed using `console.log()`.

This program demonstrates the creation of a hotel object using object literal syntax, access of
properties, and invocation of methods associated with the object. You can create as many hotel
objects as needed with their own unique properties and behavior.

You might also like