Categories
React Answers

How to highlight text using React?

To highlight text using React, we can use the react-highlighter module.

To install it, we run

npm i react-highlighter

Then we write

const Highlight = require("react-highlighter");

<Highlight search="brown">
  The quick brown fox jumps over the lazy dog
</Highlight>

to use the Highlight component to highlight 'brown' in 'The quick brown fox jumps over the lazy dog'.

Categories
JavaScript Answers

How to enable CORS in production with Nest.js?

To enable CORS in production with Nest.js, we call the enableCors method.

For instance, we write

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);

to call create to create a Nest.js app.

Then we call enableCors to enable CORS on the app.

Categories
JavaScript Answers

How to add a time delayed redirect with JavaScript?

To add a time delayed redirect with JavaScript, we call setTimeout.

For instance, we write

setTimeout(() => {
  window.location.href = "/blog";
}, 2000);

to call setTimeout with a callback to redirect to the /blog page after 2000 milliseconds.

Categories
JavaScript Answers

How to get the day of the week from the day number in JavaScript?

To get the day of the week from the day number in JavaScript, we use the date getDay method.

For instance, we write

const dayOfTheWeek = (day, month, year) => {
  const weekday = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  return weekday[new Date(`${month}/${day}/${year}`).getDay()];
};

console.log(dayOfTheWeek(3, 11, 2022));

to define the dayOfTheWeek function.

In it, we put the month, day and year into a string to create a Date object from it.

Then we call getDay to get the day of the week with 0 being Sunday, 1 being Monday, etc.

We use that returned number as the index of weekday to get the day of the week.

Categories
JavaScript Answers

How to get the day of the week from the day number in JavaScript?

To get the day of the week from the day number in JavaScript, we call the toLocaleString method.

For instance, we write

const weekday = new Date().toLocaleString("en-us", { weekday: "long" });

to call toLocaleString on a date object with the locale and an object specifying the date string returned.

We set weekday to 'long' to return the day of the week.