Categories
JavaScript Answers

How to Convert a String to a Date Object in JavaScript?

Sometimes, we have a date string that we want to convert to a date object in JavaScript.

In this article, we’ll look at how to convert a date string to a date object in JavaScript.

Extract the Parts of the Date String and Pass Them to the Date Constructor

One way to create a JavaScript date object from a date string is to extract the date parts from the date string and pass them all into the Date constructor.

For instance, we can write:

const [year, month, day] = '2020-04-03'.split('-');
const date = new Date(year, month - 1, day);
console.log(date.toDateString());

We call split on the date string with '-' to split the date string by the dash.

Then we destructure the year , month , and day from the split string array.

Next, we pass all of that into the Date constructor.

We’ve to subtract 1 from month since the month’s value that the Date constructor accepts is from 0 to 11, where 0 is for January and 11 is for December.

Then we get ‘Fri Apr 03 2020’ from the toDateString method.

We can also massage a date into an ISO date string and pass that into the Date constructor.

For instance, we can write:

const st = "26.04.2020";
const pattern = /(d{2}).(d{2}).(d{4})/;
const date = new Date(st.replace(pattern, '$3-$2-$1'));
console.log(date)

We get the parts of the date string with the pattern regex object.

Then we call replace on the st string and move the parts with the $ placeholder.

d extract digits.

The number in the curly braces is the number of digits to extract.

$1 is the first extracted part, which is '26'

$2 is the 2nd extracted part, which is '04'

And $3 is the 3rd extracted part, which is '2020' .

The Date constructor will create a UTC date.

So we get that date in string form is 'Sat Apr 25 2020 17:00:00 GMT-0700 (Pacific Daylight Time)’ .

moment.js

We can pass in a date string into moment.js’ moment function to convert it into an object we can manipulate.

For instance, we can write:

const momentDate = moment("12-25-2020", "MM-DD-YYYY");

to create a moment date object with the date string format specified in the 2nd argument.

We can use the isValid method to check for a valid date:

const isValid = moment("abc").isValid()
console.log(isValid)

isValid should false since 'abc' isn’t a valid date.

And we can convert a moment date object to a native JavaScript Date instance with toDate :

const date = moment("12-25-2020", "MM-DD-YYYY").toDate();
console.log(date)

Conclusion

To convert a date string to a JavaScript date object, we can either extract the parts of the date string ourselves and put it into the Date constructor.

Or we can use a third-party library like moment.js to help us make the job easier.

Categories
JavaScript Answers

How to Capture the Content of an HTML Canvas as an Image File?

Sometimes we may want to capture the content of an HTML canvas as an image file.

In this article, we’ll look at ways that we can do that with JavaScript.

Capturing the Canvas

We can capture the canvas by using the toDataURL method that comes with the canvas element object.

For instance, we can write the following HTML:

<canvas></canvas>

Then we can write the following JavaScript to draw some content and capture it as an image file:

const canvas = document.querySelector("canvas");  
const context = canvas.getContext("2d");  
context.fillStyle = "lightblue";  
context.fillRect(50, 50, 100, 100);  
window.location = canvas.toDataURL("image/png");

We get the canvas element with querySelector .

Then we get the canvas context with getContext .

Then we set the fill style with fillStyle .

And we draw a rectangle with fillRect .

Then we just call toDataURL on the canvas with the MIME type of the file we want to generate to capture the canvas and turn it into a base64 string.

Capturing the Canvas to PDF

To capture the canvas and turn it into a PDF, we can use the jaPDF library.

To use it, we write the following HTML:

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>  
<canvas></canvas>

Then we can add the JavaScript code to do the capture by writing:

const { jsPDF } = window.jspdf;  
const canvas = document.querySelector("canvas");  
const context = canvas.getContext("2d");  
context.fillStyle = "lightblue";  
context.fillRect(50, 50, 100, 100);  
const imgData = canvas.toDataURL("image/png");  
const doc = new jsPDF('p', 'mm');  
doc.addImage(imgData, 'PNG', 10, 10);  
doc.save('sample.pdf');

First we get the jsPDF object from the jspdf global variable added from the script tag.

Then the next 4 lines are the same as in the previous example.

Then we call canvs.toDataURL and assign the returned base64 string to imgData .

Next, we create a new jsPDF document object with the jsPDF constructor.

The first argument is the orientation of the document. p means portait.

The 2nd argument is the unit, and mm is millimeters.

Then we call addImage with imgData to add the image to our document.

The 2nd argument is the format.

The 3rd and 4th arguments are the x and y coordinates of the image relative to the upper edge of the page.

Then we call doc.save with the file name and extension to save the PDF.

Conclusion

We can capture a canvas’ content to an image with the toDataURL method.

And we can put the image into a PDF with the jsPDF library.

Categories
JavaScript Answers

How to Detect a Mobile Device with JavaScript?

With web apps being used on mobile devices more than ever, checking for a mobile device in a web app is something that we need to do often.

In this article, we’ll look at how to detect if a mobile device is being used to run a web app with JavaScript.

Use Agent Detection

One way to check for a mobile device is to check the user agent.

This isn’t the best way to check if a user is using a mobile device since user agent strings can be spoofed easily.

However, it’s still an easy way to check what device is being used by the user.

To get the user agent string, we can use the navigator.userAgent property.

For instance, we can write:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
  //...
}

We check for all the relevant keywords that indicate the user is using a mobile device with our web app with the regex.

Check Screen Size

We can also check the size of the screen that the user is loading the web app in.

For instance, we can write:

const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

if (isMobile) {
  //...
}

If max-width is 760px or less, then we know the user is loading the web app on a mobile device.

The pixels are scaled in a mobile device so that the screen width is less than 760px for mobile devices also.

Check for Touch Events

We can also check for touch events in our JavaScript code.

For instance, we can write:

const isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));

If the ontouchstart event is available in the browser, then it’s probably a mobile device since most mobile devices have touch screens.

The navigator.platform Property

The navigator.platform property also has a user agent string.

It’s more reliable than the navigation.userAgent property.

For instance, we can use it by writing:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // ...
}

Conclusion

We can detect whether a user is using a web app on a mobile device with JavaScript.

One way to check is to check the user agent.

Another way to check is to check screen sizes.

And we can also check if touch events are available in the browser.

Categories
JavaScript Answers

How to Copy a JavaScript Array by its Values?

Copying JavaScript arrays is something that we’ve to do often in our apps.

In this article, we’ll look at how to copy a JavaScript array by its values.

Array.prototype.slice

We can use the slice method available in a JavaScript array instance.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.slice();
console.log(newArray);

The slice method returns a copy of the array it’s called on if no arguments are passed into it.

Spread Operator

Another way to copy an array’s entries into another array is to use the spread operator.

This is available since ES6.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = [...oldArray];
console.log(newArray);

We copy all the items from the oldArray into the newArray with the spread operator.

So newArray is the exact copy of oldArray .

Array.prototype.concat

We can also use the concat method to copy an array to a new array.

To use it, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = [].concat(oldArray);
console.log(newArray);

concat returns the array it’s called on with the array that’s passed into it as the argument.

Also, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.concat();
console.log(newArray);

which also returns a copy of oldArray .

JSON.stringify and JSON.parse

We can use JSON.stringify and JSON.parse to make a copy of an array.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = JSON.parse(JSON.stringify(oldArray));
console.log(newArray);

JSON.stringify converts oldArray to a JSON string.

Then we use JSON.parse to convert the JSON string back to an array.

And then we assigned the returned value to newArray .

Array.from

Another way to copy an array is to use the Array.from method.

The method lets us create an array from other arrays or an array-like object.

To use it to copy an array we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = Array.from(oldArray);
console.log(newArray);

We just pass in the array we want to copy into the method and it’ll be copied.

Lodash

Lodash has the clone method to do a shallow clone of an object.

It also has the cloneDeep method to do a deep clone of an object.

We can use either one to copy an array.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = _.clone(oldArray)
console.log(newArray);

or:

const oldArray = [1, 2, 3, 4, 5];
const newArray = _.cloneDeep(oldArray)
console.log(newArray);

to make a copy of oldArray and assign it to newArray .

Conclusion

There are many ways to copy an array into another one with JavaScript’s standard libraries.

We can also do the same thing with Lodash.

Categories
JavaScript Answers

How to Get All Unique Values in a JavaScript Array?

Removing duplicate values from an array is something that we’ve to do sometimes in our JavaScript apps.

In this article, we’ll look at how to get all unique values from a JavaScript array.

The filter Method

We can use an array instance’s filter method to filter out any duplicate values that are found.

For instance, we can write:

const onlyUnique = (value, index, arr) => {
  return arr.indexOf(value) === index;
}

const a = ['a', 1, 'a', 2, '1'];
const unique = a.filter(onlyUnique);

We have the onlyUnique function that we use as the callback for the filter method.

The callback for the filter method accepts the value that we’re iterating through as the first parameter.

The 2nd parameter is the index of the element we’re iterating through.

arr is the array we’re iterating through.

So we can call indexOf or arr to get the index of the first instance of value .

If it isn’t the same as index , then we know it’s a duplicate value.

We can pass the function into the filter method to get the unique value.

Therefore, unique is [“a”, 1, 2, “1”]

Converting to a Set and Back to an Array

Another way that we can remove duplicates from an array is to convert an array into a set and then convert the set back to an array.

We can convert a set to an array with the spread operator since a set is an iterable object.

For instance, we can write:

const a = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(a)];
console.log(unique)

We create a set with the Set constructor.

This will create a set, which doesn’t allow duplicate values inside it.

So all the duplicate values will be removed.

Then we use the spread operator to convert the set back to an array.

unique should be the same value as before.

Lodash

Lodash has the uniq method that returns an array with the duplicate values removed.

For instance, we can write:

const a = ['a', 1, 'a', 2, '1'];
const unique = _.uniq(a)
console.log(unique)

to remove all the duplicate items from a .

Conclusion

We can remove duplicate items from an array with sets and the spread operator.

Also, we can do the same thing with the filter and indexOf methods.

And we can also use Lodash to remove duplicate items from an array.