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
React Answers

How to Update a React Context from Inside a Child Component?

To update a React Context from inside a child component, we can wrap the React Context provider around the child components.

Then we set the value prop of the context provider to the the state setter function that lets us update the context value.

Then we can use the useContext hook to access the context.

For instance, we write:

import React, { useContext, useState } from "react";

const Context = React.createContext();

const Foo = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("foo")}>foo</button>
    </div>
  );
};

const Bar = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("bar")}>bar</button>
    </div>
  );
};

export default function App() {
  const [val, setVal] = useState();

  return (
    <Context.Provider value={[val, setVal]}>
      <Foo />
      <Bar />
      <p>{val}</p>
    </Context.Provider>
  );
}

to create the Context context with the React.createContext method.

Next, we create the Foo component which calls the useContext hook with Context to return the value of its value prop.

In both Foo and Bar, we call setVal to set the value of val`.

val and setVal are passed down from the array we set as the value of the value prop of Context.Provider.

Since Foo and Bar are inside Context.Provider we can access the context’s value prop value with useContext.

Therefore, when we click the buttons, we see the val value in App change.

Categories
React Answers

How to Fix the ‘React eslint error missing in props validation’ When Developing a React App?

Sometimes, we run into the ‘React eslint error missing in props validation’ when developing a React app.

In this article, we’ll look at how to fix the ‘React eslint error missing in props validation’ when developing a React app.

Fix the ‘React eslint error missing in props validation’ When Developing a React App?

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.

For instance, we write:

import React from "react";
import PropTypes from "prop-types";

const Foo = ({ someProp, onClick }) => {
  return <div onClick={onClick}>foo {someProp}</div>;
};

Foo.propTypes = {
  someProp: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired
};

export default function App() {
  const onClick = () => console.log("clicked");

  return <Foo someProp={2} onClick={onClick} />;
}

to import the prop-types package to let us add prop type validation to the Foo component.

We install it by running:

npm i prop-types

We set the Foo.propTypes property to an object that has the prop names as the keys and the corresponding prop types as the values.

So someProp is a number and it’s required.

And onClick is a function and it’s also required.

Then in App, we render the Foo component with the props passed in.

Now we won’t get any errors from ESLint.

Conclusion

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.