Categories
JavaScript Answers

How to Convert a File Input Value to a Byte Array with JavaScript?

Sometimes, we want to convert a file input value to a byte array with JavaScript.

In this article, we’ll look at how to convert a file input value to a byte array with JavaScript.

Convert a File Input Value to a Byte Array with JavaScript

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

For instance, if we have the following HTML:

<input type='file'>

Then we can write:

const input = document.querySelector('input')
const reader = new FileReader();
const fileByteArray = [];

input.addEventListener('change', (e) => {
  reader.readAsArrayBuffer(e.target.files[0]);
  reader.onloadend = (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
      for (const a of array) {
        fileByteArray.push(a);
      }
      console.log(fileByteArray)
    }
  }
})

to get the input with document.querySelector .

Then we create a FileReader instance with:

const reader = new FileReader();

And we create a byte array with:

const fileByteArray = [];

Next, we call reader.readAsArrayBuffer in the file input’s change event listener to read the file into an array buffer.

Then we set the onloadend function to a function that runs when the file is loaded.

In the function, we get the buffer result with assign it to arrayBuffer .

Then we create the Uint8Array and assign it to array .

Finally, we push all the array entries into the fileByteArray .

Conclusion

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

Categories
JavaScript Answers

How to Stringify an ES6 Class Property with Getter or Setter into JSON?

Sometimes, we want to stringify an ES6class property with getter or setter into JSON.

In this article, we’ll look at how to stringify an ES6class property with getter or setter into JSON.

Stringify an ES6 Class Property with Getter or Setter into JSON

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.

For instance, we can write:

class MyClass {
  constructor(property) {
    this.property = property
  }

  set property(prop) {
    this._property = prop
  }

  get property() {
    return this._property
  }

  toJSON() {
    return {
      property: this.property
    }
  }
}

console.log(JSON.stringify(new MyClass('foo')))

to add the property property into the MyClass class.

We have the this.property instance property which is formed with getters and setters.

We just return an object with this.property set to the property property in toJSON to include.

Then when we create a new MyClass instance, we should see the this.property logged when we cal JSON.stringify on the MyClass instance.

Conclusion

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.

Categories
JavaScript Answers

How to Calculate the UTC Offset Given a Time Zone String in JavaScript?

Sometimes, we want to calculate the UTC offset given a time zone string in JavaScript.

In this article, we’ll look at how to calculate the UTC offset given a time zone string in JavaScript.

Calculate the UTC Offset Given a Time Zone String in JavaScript

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.

For instance, we can weite:

const getTimezoneOffset = (d, timeZone) => {
  const a = d.toLocaleString("ja", {
    timeZone
  }).split(/[/s:]/);
  a[1]--;
  const t1 = Date.UTC(...a);
  const t2 = new Date(d).setMilliseconds(0);
  return (t2 - t1) / 60 / 1000;
}

console.log(getTimezoneOffset(new Date(2016, 0, 1), "America/New_York"))

to create the getTimezoneOffset function that takes the d date and timeZone .

We get the date parts in an array with the toLocaleString method which we called with the timeZone .

Then we subtract the month number by 1 to match the JavaScript convention with:

a[1]--;

Next, we call Date.UTC with the a array spread as the arguments to create t1

Then we create t2 with 0 milliseconds.

Next, we subtract t2 and t1 and divide that by 60 seconds and return that.

Now we get the time zone offset in minutes.

Conclusion

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.

Categories
React Answers

How to Retrieve Values from a Select Element with Multiple Options in React?

Sometimes, we want to retrieve values from a select element with multiple options in React.

In this article, we’ll look at how to retrieve values from a select element with multiple options in React.

Retrieve Values from a Select Element with Multiple Options in React

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [val, setVal] = useState([]);

  const handleChange = (e) => {
    const value = Array.from(
      e.target.selectedOptions,
      (option) => option.value
    );
    setVal(value);
  };

  return (
    <div className="App">
      <select multiple value={val} onChange={handleChange}>
        <option value={1}>First option</option>
        <option value={2}>Second option</option>
        <option value={3}>Third option</option>
      </select>
    </div>
  );
}

We create the val state to store the selected values with the useState hook.

Then we create the handleChange function to get the values from the e.target.selectedOptions by calling Array.from with a callback to map them to the value of each option selected.

e.target.selectedOptions has the selected options.

We then call setVal with value to set val to value .

Then finally, we add the select element with the multiple prop to let us pick multiple options.

We also set the value prop to val to let us see the values we selected.

And we set onChange to handleChange to set val to the updated variables.

Conclusion

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

Categories
JavaScript Answers

How to Change the First Letter of Each Word to Upper Case with JavaScript?

To change the first letter of each word to upper case with JavaScript, we can use the JavaScript string’s replace method with a callback to change the first letter of each word to uppercase.

For instance, we can write:

const str = "hello world";
const newStr = str.toLowerCase().replace(/b[a-z]/g, (letter) => {
  return letter.toUpperCase();
});
console.log(newStr)

We call str.toLowerCase to convert str to lower case.

Then we call replace on it with a regex to match all lowercase letters that are the first letter of a word with /b[a-z]/g .

The callback gets the matched letter and call toUpperCase on it.

Therefore, newStr is 'Hello World' .