Categories
JavaScript Answers

How to exclude weekends between two dates using Moment.js and JavaScript?

You can use Moment.js along with JavaScript to exclude weekends (Saturdays and Sundays) between two dates.

To do this we:

  1. Create Moment.js objects for the start and end dates.
  2. Iterate through the dates between the start and end dates.
  3. Check if each date falls on a weekend.
  4. Exclude weekends from the list of dates.

Here’s a code example demonstrating this:

const moment = require('moment');

function getWeekdayDates(startDate, endDate) {
    const dates = [];
    let currentDate = moment(startDate);
    const endDateMoment = moment(endDate);

    while (currentDate.isSameOrBefore(endDateMoment)) {
        // Check if the current date is not a Saturday (6) or Sunday (0)
        if (currentDate.day() !== 6 && currentDate.day() !== 0) {
            dates.push(currentDate.clone().toDate()); // Add the date to the array
        }
        // Move to the next day
        currentDate.add(1, 'day');
    }

    return dates;
}

// Example usage:
const startDate = '2024-04-01'; // Start date (YYYY-MM-DD format)
const endDate = '2024-04-15'; // End date (YYYY-MM-DD format)

const weekdayDates = getWeekdayDates(startDate, endDate);
console.log(weekdayDates);

This code will output an array containing dates between startDate and endDate, excluding weekends.

Ensure you have Moment.js installed via npm or include it via a CDN in your HTML file if you’re using it in a browser environment.

Categories
JavaScript Answers

How to create A Blank HTML Space On The Fly with JavaScript?

To create a blank HTML space dynamically using JavaScript, you can create an empty HTML element such as a <div> or a <span> and then append it to the document.

To do this we can write something like

// Create a new empty div element
var blankSpace = document.createElement('div');

// Set its style to create space
blankSpace.style.width = '100px'; // Set the desired width
blankSpace.style.height = '100px'; // Set the desired height

// Optionally, set other styles like background color, border, etc.
blankSpace.style.backgroundColor = 'lightgray';
blankSpace.style.border = '1px solid black';

// Append the blank space to the document body or any other parent element
document.body.appendChild(blankSpace);

In this example, a <div> element is created dynamically with a specified width and height.

You can adjust the width, height, and other CSS properties to customize the appearance of the blank space according to your requirements.

You can also use a <span> element or any other HTML element depending on your use case.

Categories
JavaScript Answers

How to validate a URL in Node.js?

You can validate a URL in Node.js using regular expressions or by utilizing built-in modules like url.

We can do this 2 ways.

Using Regular Expressions:

function isValidURL(url) {
    // Regular expression for a valid URL
    var urlRegex = /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|localhost)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
    return urlRegex.test(url);
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Using the url Module:

const url = require('url');

function isValidURL(urlString) {
    try {
        new URL(urlString);
        return true;
    } catch (error) {
        return false;
    }
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Both methods provide a way to check if a given string is a valid URL.

The second method using the url module is more concise and reliable because it leverages built-in functionality.

Categories
JavaScript Answers

How to check if object is a DOM element with JavaScript?

To check if an object is a DOM element in JavaScript, you can use the instanceof operator along with the HTMLElement or Node interface.

To do this we can write

function isDOMElement(obj) {
    return obj instanceof HTMLElement || obj instanceof Node;
}

// Example usage:
var element = document.getElementById('myElement');
console.log(isDOMElement(element)); // Output: true

var notElement = "This is not an element";
console.log(isDOMElement(notElement)); // Output: false

In this example, the isDOMElement function takes an object as an argument and returns true if the object is an instance of HTMLElement or Node, indicating that it’s a DOM element. Otherwise, it returns false.

You can also use other methods like nodeType or nodeName to perform similar checks, but using instanceof with HTMLElement or Node is a commonly used approach.

Categories
JavaScript Answers

How to dynamically resizing Image-maps and images with JavaScript?

Resizing image maps dynamically with JavaScript involves a few steps:

Determine the size of the image element dynamically using JavaScript.

Then we modify the coordinates of the areas within the image map to match the new size of the image.

Finally we update the image map with the new coordinates.

For example we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Image Map Resizing</title>
<script>
    function resizeImageMap() {
        var img = document.getElementById('resizable-image');
        var width = img.clientWidth;
        var height = img.clientHeight;

        var areas = document.getElementsByTagName('area');
        for (var i = 0; i < areas.length; i++) {
            var coords = areas[i].getAttribute('coords').split(',');
            for (var j = 0; j < coords.length; j++) {
                if (j % 2 === 0) {
                    coords[j] = Math.round((coords[j] / img.naturalWidth) * width);
                } else {
                    coords[j] = Math.round((coords[j] / img.naturalHeight) * height);
                }
            }
            areas[i].setAttribute('coords', coords.join(','));
        }
    }
</script>
</head>
<body>
    <img id="resizable-image" src="example.jpg" onload="resizeImageMap()">
    <map name="image-map">
        <area shape="rect" coords="10,10,50,50" href="#">
        <area shape="circle" coords="100,100,30" href="#">
    </map>
</body>
</html>

In this example, resizeImageMap() is called when the image is loaded.

It calculates the width and height of the image and adjusts the coordinates of the areas accordingly.

We can adapt this code to fit your specific requirements and improve it further, such as handling different types of shapes in the image map or updating the image map dynamically as the window is resized.