Categories
JavaScript Answers

How to validate an email address in JavaScript?

Sometimes, we want to validate an email address in JavaScript.

In this article, we’ll look at how to validate an email address in JavaScript.

How to validate an email address in JavaScript?

To validate an email address in JavaScript, we can use a regex.

For instance, we write

const validateEmail = (email) => {
  const re = /\S+@\S+\.\S+/;
  return re.test(email);
};

console.log(validateEmail("anystring@anystring.anystring"));

to define the validateEmail function that takes the email string.

In it, we define the re regex that matches the segments of the email.

\S+ matches any non space characters.

@ matches @. And “\S+.\S+/` matches the email domain.

Then we call re.test with email to validate that email is an email string.

Conclusion

To validate an email address in JavaScript, we can use a regex.

Categories
JavaScript Answers

How to add event binding on dynamically created elements with JavaScript?

Sometimes, we want to add event binding on dynamically created elements with JavaScript.

In this article, we’ll look at how to add event binding on dynamically created elements with JavaScript.

How to add event binding on dynamically created elements with JavaScript?

To add event binding on dynamically created elements with JavaScript, we can use event delegation.

For instance, we write

const hasClass = (elem, className) => {
  return elem.classList.contains(className);
};

document.addEventListener(
  "click",
  (e) => {
    if (hasClass(e.target, "foo")) {
      console.log("foo");
    } else if (hasClass(e.target, "bar")) {
      console.log("bar");
    } else if (hasClass(e.target, "baz")) {
      console.log("baz");
    }
  },
  false
);

to call document.addEventListener with 'click' to listen for all clicks events on the page.

In the click event handler, we get the element we clicked on with e.target.

Then we call hasClass to check if the class has the given className.

We use elem.classList.contains to check if the className is included in the class attribute of the element.

Conclusion

To add event binding on dynamically created elements with JavaScript, we can use event delegation.

Categories
JavaScript Answers

How to fix JavaScript Date.parse giving incorrect results?

Sometimes, we want to fix JavaScript Date.parse giving incorrect results.

In this article, we’ll look at how to fix JavaScript Date.parse giving incorrect results.

How to fix JavaScript Date.parse giving incorrect results?

To fix JavaScript Date.parse giving incorrect results, we can split the date string into its parts and the use the Date constructor.

For instance, we write

const parseDate = (input) => {
  const [year, month, day] = input.split("-");
  return new Date(year, month - 1, day);
};

to create the parseDate function that splits the input date string by the dashes.

Then we pass the destructured values from the array into the Date constructor.

We subtract month by 1 since JavaScript expects the month to be 0 to 11, with 0 being January and 11 being December.

Finally, we return the created Date instance.

Conclusion

To fix JavaScript Date.parse giving incorrect results, we can split the date string into its parts and the use the Date constructor.

Categories
JavaScript Answers

How to get query string values in JavaScript?

Sometimes, we want to get query string values in JavaScript.

In this article, we’ll look at how to get query string values in JavaScript.

How to get query string values in JavaScript?

To get query string values in JavaScript, we can use the URLSearchParams constructor.

For instance, we write

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

to create the URLSearchParams instance with the query string of the current URL.

window.location.search has the query string.

Then we get the returned query parameters in an iterable object with urlSearchParams.entries().

Finally, we covert the iterable object to a plain objectg with Object.fromEntries.

The keys of params has the query parameter keys and the values are the query parameter values.

Conclusion

To get query string values in JavaScript, we can use the URLSearchParams constructor.

Categories
JavaScript Answers

How to Store Objects in HTML5 localStorage with JavaScript?

To store objects in HTML5 localStorage with JavaScript, we can use JSON.stringify to convert the JavaScript object into a string.

Then we use the localStorage.setItem method to save the stringified JSON object into local storage.

For instance, we write

const testObject = {
  'one': 1,
  'two': 2,
  'three': 3
};

localStorage.setItem('testObject', JSON.stringify(testObject));

const retrievedObject = localStorage.getItem('testObject');

console.log(jSON.parse(retrievedObject));

to call JSON.stringify with testObject to return the string version of testObject.

Then we call setItem with the key of the local storage entry and the value set to the stringifyed JSON object.

We have to convert testObject to a string before storing it with setItem since local storage only store strings.

When we want to retrieve the item, we call localStorage.getItem with the 'testObject' key.

And then we call JSON.parse with the retrievedObject string to convert the string back to JavaScript object.