Categories
JavaScript Answers

How to Convert a String of Numbers to an Array of Numbers in JavaScript?

Sometimes, we have a string with a comma-separated list of numbers that we want to convert to an array of numbers.

In this article, we’ll look at how to convert a string of numbers to an array of numbers in JavaScript.

Using String and Array Methods

We can use the split method available with JavaScript strings to convert a string into an array of strings by splitting the string by a separator.

So we can use the split method to split the string into an array of strings by the commas.

So it’ll return an array of strings with the stuff between the commas.

Then we can call the array map method to map the split string array entries into numbers.

For instance, we can write:

const nums = "1,2,3,4".split(`,`).map(x => +x)
console.log(nums)

We call split with the comma to separate the string into an array with the number strings in it.

Then we call map with a callback that converts each entry to a number with the unary + operator.

Therefore, nums is [1, 2, 3, 4] as a result.

Instead of using the unary + operator, we can also use the parseInt function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseInt(x, 10))
console.log(nums)

parseInt takes 2 arguments.

The first argument is the value we want to convert to a number.

The 2nd argument is the base that we want the returned number to be in.

So 10 would convert x to a decimal number.

Therefore, we get the same result as before.

Another way to convert the strings to numbers is to use the Number function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => Number(x))
console.log(nums)

and we get the same thing.

Number always convert to decimal numbers so we don’t have to specify it.

There’s also the parseFloat function that converts a value to a floating-point number if we want to do that.

It takes the same argument as parseInt .

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseFloat(x, 10))
console.log(nums)

And we get the same result as before for nums .

Conclusion

We can convert a string of numbers to an array of numbers with some string, array and number functions.

Categories
JavaScript Answers

How to Get the Start and the End of a Day in JavaScript?

Sometimes, we may want to get the start and end of a day with JavaScript.

In this article, we’ll look at ways to get the start and end of a day with JavaScript.

Using Native Date Methods

One way to get the start and end of a day with JavaScript is to use native date methods.

We can use the setHours method to set the hours of a day to the start or end of a day.

For instance, we can write:

const start = new Date(2020, 1, 1, 1, 1);
start.setHours(0, 0, 0, 0);
console.log(start)

We create the start date with the Date constructor.

Then we call setHours with all zeroes to set the time of the date to midnight.

So start is:

Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)

if we’re in Pacific time.

Likewise, we can use setHours to set the hours, minutes, seconds, and milliseconds to the end of the date.

To do this, we write:

const end = new Date(2020, 1, 1, 1, 1);
end.setHours(23, 59, 59, 999);
console.log(end)

to create a date and set it to the end of the date by passing in a few arguments.

23 is the hours.

The first 59 is the minutes.

The second 59 is the seconds.

And 999 is the milliseconds.

Therefore, end is:

Sat Feb 01 2020 23:59:59 GMT-0800 (Pacific Standard Time)

after calling setHours .

Using Moment.js

Alternatively, we can use the moment.js library to return the start and end of a date.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).startOf('day');
console.log(start.toString())

to create a moment object with the moment function with a JavaScript native date object as its argument.

Then we call startOf with 'day' to return a moment object with the time set to the start of the day.

So we get:

Sat Feb 01 2020 00:00:00 GMT-0800

as the value of start.toString() if we’re in the Pacific time zone.

Likewise, we can use the endOf method to get the end of the date.

To do this, we write:

const end = moment(new Date(2020, 1, 1, 1, 1)).endOf('day');
console.log(end.toString())

We call endOf instead of startOf .

And then end.toString() returns Sat Feb 01 2020 23:59:59 GMT-0800 if we’re in the Pacific time zone.

We can also convert the time zone to UTC before call startOf and endOf with the utc method.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).utc().startOf('day');
console.log(start.toString())

const end = moment(new Date(2020, 1, 1, 1, 1)).utc().endOf('day');
console.log(end.toString())

to do the conversion.

Then start.toString() returns:

Sat Feb 01 2020 00:00:00 GMT+0000

And end.toString() returns:

Sat Feb 01 2020 23:59:59 GMT+0000

Conclusion

We can get the start and end of a date with JavaScript with native date methods or moment.js.

Categories
JavaScript Answers

How to Remove Everything After a Certain Character in a JavaScript String?

Sometimes, we may want to remove everything after a given character in our JavaScript string.

In this article, we’ll look at how to remove everything after a certain character in our JavaScript string.

String.prototype.split

We can split a string with the split method.

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const [path] = url.split('?')
console.log(path)

to get the path string before the question mark with split .

split returns an array of substrings separated by the given character.

So we can destructure the returned array and get the first item.

Therefore, path is: '/Controller/Action’ .

String.prototype.indexOf and String.prototype.substring

The indexOf method lets us get the index of the given character in a string.

We can use it with the substring method to extract the substring from the beginning to the given index returned by indexOf .

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const path = url.substring(0, url.indexOf('?'));
console.log(path)

We call url.indexOf('?') to get the index of the question mark character.

Then we pass that into substring as the 2nd argument.

0 as the first argument means we get the substring from the first character to the index passed in the 2nd argument.

So path has the same value as before.

Regex Replace

We can also call the string replace method with a regex to remove the part of the string after a given character.

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const path = url.replace(/\?.*/, '');
console.log(path)

The /\?.*/ regex matches everything from the question to the end of the string.

Since we passed in an empty string as the 2nd argument, all of that will be replaced by an empty string.

replace returns a new string with the replacement applied to it.

So path is the same value as before.

Conclusion

There are several ways we can use to extract the part of the string after the given character with several string methods.

Categories
JavaScript Answers

How to Detect Page Zoom Levels in Modern Browsers with JavaScript?

Sometimes, we may want to detect page zoom levels in modern browsers with JavaScript.

In this article, we’ll look at how to detect zoom levels in modern browsers with JavaScript.

Using the window.devicePixelRatio Property

One way to detect the browser zoom level is to use the window.devicePixelRatio property.

For instance, we can write:

window.addEventListener('resize', () => {
  const browserZoomLevel = Math.round(window.devicePixelRatio * 100);
  console.log(browserZoomLevel)
})

When we zoom in or out, the resize event will be triggered.

So we can listen to it with addEventListener .

In the event handler callback, we get the window.devicePixelRatio which has the ratio between the current pixel size and the regular pixel size.

Divide outerWidth by innerWidth

Since outerWidth is measured in screen pixels and innerWidth is measured in CSS pixels, we can use that to use the ratio between them to determine the zoom level.

For instance, we can write:

window.addEventListener('resize', () => {
  const browserZoomLevel = (window.outerWidth - 8) / window.innerWidth;
  console.log(browserZoomLevel)
})

Then browserZoomLevel is proportional to how much we zoom in or out.

Conclusion

We can detect page zoom levels with the window.devicePixelRatio property or the ratio between the outerWidth and innerWidth .

Categories
JavaScript Answers

How to Display JavaScript DateTime in 12 Hour AM/PM Format?

Sometimes, we may want to display a JavaScript date-time in 1 hour AM/PM format.

In this article, we’ll look at how to format a JavaScript date-time into 12 hour AM/PM format.

Create Our Own Function

One way to format a JavaScript date-time into 12 hour AM/PM format is to create our own function.

For instance, we can write:

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes.toString().padStart(2, '0');
  let strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date(2021, 1, 1)));

We have the formatAMPM function that takes a JavaScript date object as a parameter.

In the function, we call getHours tio get the hours in 24 hour format.

minutes get the minutes.

Then we create the ampm variable and it to 'am' or 'pm' according to the value of hours .

And then we change the hours to 12 hour format by using the % operator to get the remainder when divided by 12.

Next, we convert minutes to a string with toString and call padStart to pad a string with 0 if it’s one digit.

Finally, we put it all together with strTime .

So when we log the date, we get:

12:00 am

Date.prototype.toLocaleString

To make formatting a date-time to AM/PM format easier, we can use the toLocaleString method.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

We call toLocaleString on our date object with the locale and an object with some options.

The hour property is set to 'numeric' to display the hours in numeric format.

This is the same with minute .

hour12 displays the hours in 12-hour format.

So str is ‘1’2:00 AM’ as a result.

Date.prototype.toLocaleTimeString

We can replace toLocaleString with toLocaleTimeString and get the same result.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

And we get the same result.

moment.js

We can also use moment.js to format a date object into a 12-hour date-time format.

To do this, we call the format method.

For example, we can write:

const str = moment(new Date(2021, 1, 1)).format('hh:mm a')
console.log(str);

And we get the same result as before.

a adds the AM/PM.

hh is the formatting code for a 2 digit hour.

mm is the formatting code for a 2 digit minute.

Conclusion

We can format a JavaScript date-time to 12-hour format with vanilla JavaScript or moment.js.