Categories
JavaScript Tips

JavaScript Tips — Base64 to Blob, JSON, Dates, and Input

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.

Difference between JSON.stringify and JSON.parse

JSON.strignify and JSON.parse do different things.

JSON.stringify converts an object into a JSON string.

JSON.parse parse a JSON string into an object.

For instance, we can use JSON.stringify by writing;

const obj = { foo: 1, bar: 2 };
const str = JSON.stringify(obj);

str is the stringified version of obj .

We can use JSON.parse by writing:

const obj = JSON.parse(str);

If str is a valid JSON string, then it’ll be parsed into an object.

Remove Accents or Diacritics in a String

If our string have accents or diacritics in a string, we can remove it by using the normalize method.

For instance, we can write:

const str = "garçon"
const newStr = str.normalize("NFD").replace(/[u0300-u036f]/g, "")

Then newStr is “garcon” .

NFD means the Unicode normal form.

It decomposes the combined graphemes into the combination of simpler ones.

Therefore the ç is decomposed into the letter and the diacritic.

Then we used replace to remove all the accent characters.

Parsing JSON Giving “unexpected token o” Error

We’ll get the ‘unexpected token o’ error if the thing that we’re trying to parse is already an object.

Therefore, we should make sure that we aren’t parsing a JSON object.

Detecting Browser Language Preference

We can detect the browser language preference by using the window.navigator.userLanguage or window.navigator.language .

window.navigator.userLanguage is only available in IE.

window.navigator.language is available in other browsers.

It returns the language that’s set in Windows Regional Settings.

window.navigator.language returns the browser language and not the preferred language.

Creating a Blob from a Base64 String in JavaScript

To create a blob from a base64 string, we can use the atob function.

Then we’ve to create an array of byte values from each character of the string.

Then we convert the byte numbers array to an Uint8Array .

Then we can pass that into the Blob constructor.

Therefore, we write:

const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

to do all that.

Getting Current Date and Time

We can get the current date and time in JavaScript with various methods of the Date instance.

getDate gets the day of the month.

getDay gets the day of the week, with 0 being Sunday, 1 being Monday, etc.

getFullYear returns the full year umber.

getHours get the hours of the day.

getMinutes returns the minutes of the hour.

getSeconds get the seconds.

We can use it by writing:

const newDate = new Date();
const day = newDate.getDay();

We can also use the toLocaleString method to format our date string in a locale-sensitive manner:

new Date().toLocaleString();

Best Way to Track Change as we Type in an Input

To track changes as we type in the input box, we can listen to the input event.

For instance, we can write:

`const input = document.getElementById('input');
`const result = document.getElementById('result');

const inputHandler = (e) => {
  result.innerHTML = e.target.value;
}

source.addEventListener('input', inputHandler);

We get the input’s value in the inputHandler with e.target.input .

Also, we set the input value in the result element.

Then we call addEventListener to listen to the input event.

The Meaning of “=>” in JavaScript

=> lets us create an arrow function, which is a shorter function that doesn’t bind to this .

We can’t use arrow functions as constructor functions because of that.

It takes the value of this from whatever it is outside.

It also doesn’t bind to the arguments object, so we can’t use it to get arguments passed into a function.

Conclusion

JSON.stringify and JSON.parse are the opposite of each other.

=> lets us create arrow functions.

We can listen to the input event to get the value as user types into an input box.

Getting the current date and time can be done with date methods.

We can convert a base64 string to a blob.

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 *