Categories
JavaScript Tips

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

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.

Categories
JavaScript Tips

JavaScript Tips — Secure HTTP Server, Decoding URIs, and More

As with many kinds 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.

The Difference Between decodeURIComponent and decodeURI

decodeURI is intended for decoding the whole URI.

decodeURIComponent is used for decoding the parts between separators.

We can pass in the parts and convert it back to the original URL.

For instance, we can write:

decodeURIComponent('%26')

and get '&' ,

However, when we write:

decodeURIComponent('%26')

We get back the original string.

However, if we write:

decodeURI('%41')

or:

decodeURIComponent('%41')

'A' is returned.

This means that decodeURIomponent can decode alphanumeric values and symbols.

But decodeURI can only decode alphanumeric values.

Open URL in the Same Window and in the Same Tab

We can open URLs in the same window and tab with if we use window.open with the argument '_self' .

For example, we can write:

window.open("https://www.example.com","_self");

Then the https://example.com URL will open in the same window.

Also, we can set the URL as the value of the location.href property to do the same thing:

location.href = "https://www.example.com";

Redirecting to a Relative URL

We can redirect to a relative URL if we set location.href to a relative path.

For instance, we can write:

window.location.href = '../';

to redirect one level up.

If we want to go to a path, we can write:

window.location.href = '/path';

to go to the path relative to the current domain.

Listen to change Events in a content editable Element

If we add a contenteditable attribute to an element, we can listen to the input event to watch for inputs.

For instance, if we have:

<div contenteditable="true" `id="editor"`>enter text</div>

Then to get the data that we typed into the div, we can listen to the input event:

document.getElementById("editor").addEventListener("input", () => {
  console.log("text inputted");
}, false)

We get the editor div and attach the input listener to it.

Then we should see the console log.

Process Each Letter of Text

We can loop through each letter of text using a loop and use the charAt method.

For instance, we can write:

for (const i = 0; i < str.length; i++) {
  console.log(str.charAt(i));
}

We can also use a while loop to do the same thing:

while (i--) {
  console.log(str.charAt(i));
}

Also, we can spread it into an array and use forEach to loop through each character:

[...`str`].forEach(c => console.log(c))

We can also use a for-of loop to loop through a string directly:

for (const c of str) {
  console.log(c)
}

And we can also use the split method to split it into an array of characters and loop through it:

str.split('').forEach((c) => console.log(c));

Remove a Character from a String

To remove a character from a string, we can use the replace method to do it.

For instance, we can write:

const str = "foo";
const newStr = str.replace('f', '');

Then we remove the 'f' character from the string.

We can also do the same thing with split and join :

const newStr = str.split('f').join('');

We split the string using 'f' as the separator and return an array of the parts separated by it.

Then we use join to join the parts back together.

Difference Between console.dir and console.log

There are differences between console.dir and console.log , even though they do the same thing.

log prints out the toString representation of an object, but dir prints out the whole object tree in Firefox.

In Chrome, console.log prints out the tree most of the time.

But it still prints the stringified version in some of the cases even if it has properties.

For instance, it’ll print out the stringified form of an HTML element.

console.dir always prints the object tree.

Create an HTTPS Server in Node.js

To create an HTTPS server with Node.js, we can read the certificate and private key into the server program.

Then we set the credentials when loading the server to make it use the certificate.

For instance, we can write:

const crypto = require('crypto');
const fs = require("fs");
const http = require("http");

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end("hello worldn");
}).listen(8000);

We read the private key and certificate with the readFileSync calls.

Then we put the key and certificate in the options object.

When we call createServer , we pass in the key and certificate through the object.

Conclusion

We can iterate through each letter of the text in various ways. To create a secure HTTP server, we can read in the private key and certificate. decodeURI and decodeURIComponent are different.console.dir always print the object tree.

Categories
JavaScript Tips

JavaScript Tips — Objects, Circular JSON, and Converting Strings to Dates

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.

Print a Circular Structure in a JSON-like Format

We can use the util library to print circular structures.

It has an inspect method that lets us print these structures.

So we can write:

console.log(util.inspect(obj));

to do that.

There’s also the circular-json package that does the same thing.

We install it by running:

npm i --save circular-json

and write:

const CircularJSON = require('circular-json');
const json = CircularJSON.stringify(obj);

There’s also the flatted package.

We install it by running:

npm i flatted

Then we can write:

import {parse, stringify} from 'flatted';

const foo = [{}];
foo[0].foo = foo;
foo.push(foo);

stringify(foo);

Check if Object Property Exists with a Variable Holding the Property

We can use the hasOwnProperty method or in operator to check if a property exists.

For example, we can write:

const prop = 'prop';
if (obj.hasOwnProperty(prop)) {
  //...
}

or we can write:

const prop = 'prop';
if (prop in obj) {
  //...
}

Check if a User has Scrolled to the Bottom

We can check with plain JavaScript.

We write:

el.onscroll = () => {
  if(el.scrollTop + el.clientHeight === el.scrollHeight) {
    // ...
  }
}

We run an event handler on scroll.

To check that the user scrolled to the bottom, we check that the sum of scrollTop and clientHeight is the same as the scrollHeight .

scrollTop is the number of pixels that the element is scrolled vertically.

clientHeight is the height of the element in pixels.

Padding is included, but borders, margins, and horizontal scrollbars are excluded.

Determine Equality for Two JavaScript Objects

We use the LodashisEqual method to check for deep equality.

For instance, we can write:

_.isEqual(object, other);

Enumerate the properties of a JavaScript Object

To enumerate the properties of a JavaScript object, we can use the for-in loop or Object.keys .

For instance, we can write:

for (const p in obj) {
  if (obj.hasOwnProperty(p)){
    //...
  }
}

We call hasOwnProperty to check if a property is in an object.

This is because for-in enumerates all properties in the prototype chain.

Likewise, we can use Object.keys:

for (const p of Object.keys(obj)) {
  //...
}

We use the for-of loop instead of the for-in loop since Object.keys returns an array of the own keys.

Converting a String to a Date in JavaScript

We can use the Date constructor to parse a date string into a Date instance:

const parts = '2014-04-03'.split('-');
const date = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(date.toDateString());

We extract the date string’s year, month, and date.

Then we put them in the Date constructor.

We’ve to subtract 1 from the month because month 0 is January, 1 is February, etc.

Then we get the correct date.

Detect if a Browser Window is not Currently Active

To check if a browser window is active or not, we can watch the visibilitychange event in our code.

For instance, we can write:

document.addEventListener("visibilitychange", onchange);

Where onchange is:

const `onchange =` () => {
  if (document.hidden) {
    //...
  } else {
    //...
  }
}

We check the document.hidden property to check if a page is hidden.

Read a File One Line at a Time in Node.js

We can use the readline module to read a file one line at a time.

For instance, we cabn write:

const lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file')
});

lineReader.on('line', (line) => {
  console.log(line);
});

We use the readline module and pass in an object with the read stream for the file.

Then listen to the line event to get the lines.

JavaScript Equivalent to PHP isset()

PHP’s isset function has several equivalents in JavaScript.

We can use the typeof operator, hasOwnProperty , or the in operator.

For instance, we can write:

if (typeof obj.foo !== 'undefined') {
  // ...
}

to check if obj.foo is defined or not.

We can also write:

if (obj.hasOwnProperty('foo')) {
  // ...
}

or:

if ('foo' in obj) {
  // ...
}

Then in operator checks if the property exists in obj ‘s prototypes, so we should be aware of that.

Conclusion

There many ways to check if a property exists.

We can use libraries to print circular JSON.

Deep equality of objects can be checked with Lodash.

Categories
JavaScript Tips

JavaScript Tips — ESLint Rules, Canvas, Cleaning Local Storage

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.

Turn JavaScript Array into a Comma-Separated List

We can use the array instance’s join method to join the strings together with a comma.

For instance, we can write:

const arr = ["foo", "bar", "baz"];
console.log(arr.join(", "));

Constructors in JavaScript Objects

JavaScript objects can be created from constructors.

To create it. we write:

function Box(color) {
  this.color = color;
}

Box.prototype.getColor = function(){
  return this.color;
};

We created the Box constructor with the color instance variable.

Also, we attach the getColor method with the prototype property to return the color .

Then we can use the new operator to create a Box instance:

const box = new Box("brown");
console.log(box.getColor());

Equivalent, we can use the class syntax:

class Box {
  constructor(color) {
    this.color = color;
  }

  getColor(){
    return this.color;
  }
}

We put everything in the Box class instead of using prototypes.

However, they’re the same.

Disable ESLint Rule for a Specific File

We can disable ESLint rules for a specific file with comments.

For instance, we can write:

/* eslint no-use-before-define: 0 */

to turn off the a no-use-before-define rule.

Or we can write:

/* eslint-disable no-use-before-define */

to do the same thing.

And we can write:

/* eslint no-use-before-define: 2 */

to turn it on.

We can also tell ESLint to ignore specific files by putting the file paths in .eslintignore :

build/*.js
node_modules/**/*.js

Add a JavaScript / jQuery DOM Change Listener

To listen for DOM changes, we can listen to the DOMSubtreeModified event.

For instance, we can write:

$("#div").bind("DOMSubtreeModified", () => {
  console.log("tree changed");
});

We use jQuery’s bind method to listen to the event.

Early Exit from Function

To end a function early, we can use the return keyword.

It can be placed anywhere to end a function early.

For example, we can write:

const myfunction = () => {
  if (shouldStop) {
    return;
  }
}

Removing Items from Local Storage When the Tab or Window is Closed

To remove the item from local storage when the tab or window is closed, we can listen to the beforeunload event.

In the listener function, we can call removeItem to remove the item.

For instance, we can write:

window.onbeforeunload = () => {
  localStorage.removeItem(key);
  return '';
};

The listener should return a string.

Selecting “selected” on Selected <select> Option in a React Component

We can set the value prop of the select element to set the selected option.

For instance, we can write:

<select value={chosenItem}>
  <option value="A">apple</option>
  <option value="B">banana</option>
  <option value="O">orange</option>
</select>

We set the chosenItem state with setState in a class component.

Or we can use the state change function returned from the useState method to set it.

Resize HTML5 Canvas to Fit Window

To resize the HTML5 canvas to fit the window, we can change the width and height of the canvas with JavaScript.

For instance, we can write:

`const resizeCanvas = () => {
  const canvas =` document.getElementById('canvas'),
  `const ctx = canvas.getContext('2d');
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
}`

window.addEventListener('resize', resizeCanvas, false);

innerWidth sets the width to the window width and innerHeight sets the height to the window height.

We watch the resize event to set the dimensions.

Adding Hours to JavaScript Date Object

We can add hours to the JavaScript date object with the getTime method to get the timestamp.

Then we add the milliseconds to the timestamp to add the number of hours we want.

For example, we can write:

date.setTime(date.getTime() + (hours * 60 * 60 * 1000));

We use setTime to set the timestamp of the new date.

Check if the Array is Empty or does not Exist

To check if an array is empty or doesn’t exist, we can use the Array.isArray method and check the length property.

For instance, we can write:

if (!Array.isArray(array) || !array.length) {
  // ...
}

We check if array is an array with Array.isArray .

Then we check if the length is 0 or not with !array.length .

If both are true then we know it’s not an array

If only !array.length is true then we know that array is an empty array.

Conclusion

We can disable ESLint rules with comments or .eslintignore.

The DOMSubtreeModified is emitted when the DOM structure changed.

JavaScript objects can be created from constructors or classes.

Categories
JavaScript Tips

Useful JavaScript Tips — Numbers, Strings, and Strict Mode

As with any kind of app, JavaScript apps have to be written well otherwise we will run into all kinds of issues later on. In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Tip #1: Trim the Leading Zero in a Number String

We can trim the leading zero in a number by parsing the number string to a number.

To parse it into an integer, we can use the parseInt function.

For instance, we can write:

parseInt('010', 10)

Then we’ll parse the number string into a decimal.

If we want to parse a string into a number.

Then we can use the + operator. For instance, we can write:

+'010'

Then we get 10.

Also, we can string the leading 0 with regex and the replace method.

For instance, we can write:

number.replace(/^0+/, '')

^ means the start of the string.

Tip # 2: Replace All Occurrences of a String

We can replace all occurrences of a string with the replace method, a regex and the g flag for global replace.

For instance, we can write:

const phrase = 'I love dogs, dogs are great';  
const stripped = phrase.replace(/dog/g, 'cat');

Then we get “I love cats, cats are great” .

/dog/g is the regex. And 'cat' is what we replaced 'dog' with.

To perform a case insensitive search, we can add the i flag.

For instance, we can write:

const phrase = 'I love dogs. Dogs are great';  
const stripped = phrase.replace(/dog/gi, 'cat');

Then we get “I love cats. cats are great” .

We can also replace all substrings by using the split and join methods.

For instance, we can write:

const phrase = 'I love dogs, dogs are great';  
const stripped = `phrase.split('dog').join('cat')`;

We split the phrase string with 'dog' as the separator.

Then we call join with 'cat' so 'cat' replaces dog.

Therefore, stripped is “I love cats, cats are great” .

Tip # 3: Check if a Property is Undefined

If want to check if a property is undefined, then we can use the typeof operator.

For instance, we can write:

typeof color

Then if color is undefined, then it should return 'undefined' .

If we want to check an object property for undefined , then we can write:

typeof dog.color === 'undefined'

given that dog is an object.

Tip #4: Remove a Property from a JavaScript Object

We can remove a property from a JavaScript object by using the the delete operator.

To use it, we put delete in front of the property that we want to delete.

For instance, if we have the following object:

const dog = {  
  color: 'brown'  
}

Then we can write:

delete dog.color

Then we removed the color property from dog .

Tip #5: Redirect to Another Page

We can redirect to another page by setting a URL to the window.location object.

For instance, we can write:

window.location = 'https://example.com'

Then we go to https://example.com.

If we want to go to a relative path, then we can set the pathname property.

For instance, we can write:

window.location.pathname = '/foo'

Then we go to /foo .

We can also set the href property to go to a URL:

`window.location.href = 'https://`example`.com'`

Also, we can call the window.location.assign method to do the same thing:

window.location.assign('https://example.com')

Likewise, we can use the replace method. This rewrites the current page in history with the new URL.

We can write:

window.location.replace('https://example.com')

The browser also hs the self and top objects, which are the same as the window object.

So we can replace window with those objects.

Tip #6: Use Strict Mode

Strict mode disallows the use of some bad features in JavaScript.

To use it, we use the 'use strict' directive to enable it.

With strict mode, we can’t accidentally declare global variables.

For instance, we can’t write:

foo = 'bar';

with JavaScript strict mode on. It also disallows assignment to reserved keywords.

For example, we can’t write:

undefined = 1

Also, we can’t override object properties that are marked to be not writable.

For instance, if we have:

const dog = {}  
Object.defineProperty(dog, 'color', { value: 'brown', writable: false })

Then we can’t override the value by reassigning it.

Getter properties also can’t ve overridden with new values.

With strict mode on, we can’t add properties that we disallowed from adding properties with Object.preventExtensions .

Also, we can’t delete built-in objects with it.

Function arguments with the same name also can’t be in the same signature.

So we can’t write:

function(a, a, b) {  
  console.log(a, b)  
}

Conclusion

We can remove leading zero a number string by parsing it. There are various ways to replace all instances of a string. Strict mode is great for preventing us from adding bad code.