Categories
JavaScript Tips

JavaScript Tips — Checking File Sizes, Modular Arithmetic and More

Spread the love

As with any kind of app, there are difficult issues to solve when we write apps for JavaScript. In this article, we’ll look at some solutions to common JavaScript problems. Replace Multiple Characters in One Replace Call

We can use the g flag on the regex to replace multiple characters with one replace call.

For instance, we can write:

string.replace(/_/g, ' ').replace(/#/g, '')

We replace all instances of _ with the first call.

Then we replace all instances of # with the 2nd call.

Make the Window Full Screen with Javascript

We can use the fullscreen API to make a window full screen.

For example, we can write:

document.documentElement.`requestFullscreen();`

We just call the requestFullScreen method to change the window to full-screen mode.

Then we can call document.exitFullScreen to exit full-screen mode.

The Fastest Way to Convert JavaScript NodeList to Array

We can convert a JavaScript NodeList to an array with the spread operator or the Array.from method.

For example, we can write:

const els = Array.from(document.querySelectorAll('p'));

We can use the spread operator by writing:

const els = [...document.querySelectorAll('p')];

Capitalize the First Letter of Each Word

We can capitalize the first letter of each word with some array methods.

For instance, we can write:

str = str.toLowerCase()
  .split(' ')
  .map((s) => `${s.charAt(0).toUpperCase()}${s.substring(1)}`)
  .join(' ');

We convert the string to lower case first, then we split the words with split .

Then we call map to match each word to have the first letter upper case and the rest lower case.

Finally, we call join to join the words back together.

JavaScript File Upload Size Validation

We can validate the size of the file without using any library.

For example, we can write:

<input onchange="validateSize(this)" type="file">

Then we can write:

const validateSize = (file) => {
  const fileSize = file.files[0].size;
  if (fileSize > 2 * (1024 ** 2)) {
    console.log('File size exceeds 2 MB');
  } else {
    //...
  }
}

We just get the file.files[0].size property to validate the size of the first file selected.

file is the file input.

files has one or more selected files.

size has the size.

Add a class to a DOM Element

To add a class to a DOM element, we can use the classList property’s add method.

For example, we can write:

const element = document.querySelector('div');
element.classList.add('baz');

We get the div element, then we can use the add method of the classList to add the class name.

Using % to do Modular Arithmetic

The % operator is used for getting the remainder of one number divided by another.

But we can also use it to get the one number mod another number.

For instance, we can write:

const mod = (m, n) => `((m % n) + n) % n;`

We first get the remainder of m divided by n .

Then we add n to it to make it positive.

Finally, we get the remainder of that value divided by n .

Most Efficient Way to Concatenate N Arrays

We can concatenate one or more arrays with the push method.

To do that, we can write:

arr.push(...a, ...b)

Then all the items from a and b will be appended to arr .

We can also use concat with multiple arrays.

For instance, we can write:

arr = arr.concat(array, array1, array2, array3);

We call concat so that we put the entry of each array into a new array after the entries of arr .

Then that array is returned.

Therefore, we’ve to assign it to arr to update it with the returned value.

Find an Element in the DOM Based on an Attribute Value

We can find an element in the DOM based on an attribute value.

For instance, we can write:

const fileInput = document.querySelector("input[type=file]");

We get a file input by using querySelector .

It takes any CSS selector, including attribute selectors.

type is the attribute, file is the value.

We can also get a group of elements with the same selector by using querySelectorAll .

Conclusion

replace can be chained so we can replace more than one kind of text. A NodeList can be converted to an array with Array.from or the spread operator. We can concatenate arrays with push or concat. % can be used to do modular arithmetic if we combine it with other operations. File sizes can be checked on the client-side.

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 *