Categories
JavaScript Tips

JavaScript Tips — Parsing URLs, Reading Files, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Parse a URL into Hostname and Path

To parse a URL string into its hostname and path, we can use the URL constructor.

For instance, we can write:

new URL("http://example.com/foo/bar")

Then that returns an object with the hostname and pathname properties.

hostname is the hostname.

pathname is the pathname.

Format JavaScript Date as yyyy-mm-dd

We can format a date as a string in yyyy-mm-dd format with a few date methods.

For instance, we can write:

const d = new Date(date);
let month = (d.getMonth() + 1).toString();
let day = (d.getDate()).toString();
const year = d.getFullYear();

if (month.length < 2) {
  month = `0${month}`;
}

if (day.length < 2)  {
  day = `0${day}`;
}

const formattedDate = [year, month, day].join('-');

We create a date object from the Date constructor.

Then we call getMonth to get the month.

We’ve to add 1 because the month is zero-based.

We get the day of the month with getDate .

Also, we get the 4 digit year with getFullTear .

If the month or day is a single digit, then we put a zero before it.

Then we join the year, month, and day together with '-' .

A simpler solution would be to use the toISOString method.

For example, we can write:

const formattedDate = new Date().toISOString().slice(0, 10);

We convert the date to a string and extract the year, month, and day parts.

Check if Element is Visible in DOM

We can check if an element is visible in the DOM in a few ways.

One way is to use the offsetParent property to check for visibility.

The property will return null whenever it or its parents are hidden via the display style property.

This will be true if there are no fixed elements on the page.

If there are no fixed elements on the page, then we write:

el.offsetParent === null

where el is the element to check for visibility, to check for it.

We can also call getComputedStyle with an element as its argument to get its computed display style.

So we can write:

cpnst style = window.getComputedStyle(el);
const isInvisibie = style.display === 'none';

We check that the style.display property is 'none' .

Convert a String to a Character Array

We can split a string to a character array with the split method.

For example, we can write:

const output = "foo bar".split('');

Then we get:

["f", "o", "o", " ", "b", "a", "r"]

as the value of output .

Get Array of Object’s Keys

To get an array of an object’s keys, we can use the Object.keys method.

For example, we can write:

const obj = {
  foo: 1,
  bar: 2
};

const keys = Object.keys(obj);

Then we keys is ['foo', 'bar'] .

Create an Empty Object with {} or new Object()

There are no benefits with using new Object() .

And using {} is more compact and readable.

Therefore, we should use the object literal syntax rather than the Object constructor.

Read a Local Text File

We can read a local text file with client-side JavaScript.

To do this, we can use the FileReader constructor to do it.

We can let users select a file and read the selected text file.

For instance, we can add a file input:

<input type='file' accept='text/plain' onchange='openFile(event)'>

Then we can write:

const openFile = (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    const text = reader.result;
    consr node = document.getElementById('output');
    node.innerText = text;
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
};

We created the openFile function which takes a event parameter.

We get the input element with event.target .

Then we get the selected file with files[0] .

Next, we create a FileReader instance and call readAsText on it with the file as the argument.

Then the onload callback will run and we get the result with reader.result .

Conclusion

We can use the URL constructor to parse a URL into its parts.

The FileReader lets us read text files.

To format dates without a library, we can use toISOString or methods to get the date parts.

There are several ways to check if an element is visible.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *