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.

Categories
JavaScript Answers

How to query referenced objects in MongoDB?

Sometimes, we want to query referenced objects in MongoDB.

In this article, we’ll look at how to query referenced objects in MongoDB.

How to query referenced objects in MongoDB?

To query referenced objects in MongoDB, we can use the $lookup operator.

For instance, we write

db.Foo.aggregate(
  { $unwind: "$bars" },
  {
    $lookup: {
      from: "bar",
      localField: "bars",
      as: "bar",
    },
  },
  {
    $match: {
      "bar.testprop": true,
    },
  }
);

to call aggregate with the $lookup property set to an object with the referenced object properties we’re looking for.

We look for the collection specified with $lookup.from.

We look for the localField in the field specified in $lookup.from and we return the result in the field with the name set as the value of as.

We look for the field values in the $bars array since we set unwind to $bars.

And we search for the items with bar.testprop set to true with $match.

Conclusion

To query referenced objects in MongoDB, we can use the $lookup operator.

Categories
JavaScript Answers

How to encrypt data with a public key in Node.js?

Sometimes, we want to encrypt data with a public key in Node.js.

In this article, we’ll look at how to encrypt data with a public key in Node.js.

How to encrypt data with a public key in Node.js?

To encrypt data with a public key in Node.js, we can use the fs.readFileSync method to read the public key.

Then we use the crypt module to encrypt our data.

For instance, we write

const crypto = require("crypto");
const path = require("path");
const fs = require("fs");

const encryptStringWithRsaPublicKey = (
  toEncrypt,
  relativeOrAbsolutePathToPublicKey
) => {
  const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
  const publicKey = fs.readFileSync(absolutePath, "utf8");
  const buffer = Buffer.from(toEncrypt);
  const encrypted = crypto.publicEncrypt(publicKey, buffer);
  return encrypted.toString("base64");
};

const decryptStringWithRsaPrivateKey = (
  toDecrypt,
  relativeOrAbsolutePathtoPrivateKey
) => {
  const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey);
  const privateKey = fs.readFileSync(absolutePath, "utf8");
  const buffer = Buffer.from(toDecrypt, "base64");
  const decrypted = crypto.privateDecrypt(privateKey, buffer);
  return decrypted.toString("utf8");
};

to create the encryptStringWithRsaPublicKey and decryptStringWithRsaPrivateKey functions.

In encryptStringWithRsaPublicKey, we get the publicKey with fs.readFileSync to read the public key file.

Then we convert the toEncrypt string to a buffer with Buffer.from.

And then we call crypto.publicEncrypt to encrypt the buffer with the publicKey.

In decryptStringWithRsaPrivateKey, we read the privateKey with fs.readFileSync.

Then we get the buffer from the toDecrypt string with Buffer.from.

Next, we call crypto.privateDecrypt with privateKey and buffer to decrypt the buffer with the privateKey.

Finally, we convert the decrypted content to a string with toString.

Conclusion

To encrypt data with a public key in Node.js, we can use the fs.readFileSync method to read the public key.

Then we use the crypt module to encrypt our data.