Categories
JavaScript Answers

How to Validate ZIP Code (US Postal Code) with JavaScript?

Sometimes, we want to validate ZIP code (US postal code) with JavaScript.

In this article, we’ll look at how to validate ZIP code (US postal code) with JavaScript.

Validate ZIP Code (US Postal Code) with JavaScript

To validate ZIP code (US postal code) with JavaScript, we can use a regex that matches 5 digit numbers or 5 digit numbers with a 4 digit number separated by a dash.

For instance, we can write:

const isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
console.log(isValidZip)

to match 5 digit numbers with (^\d{5}$).

And we match 5 digit numbers with a dash and 4 digit number after it with (^\d{5}-\d{4}$).

We match both by joining both patterns with |.

Then we call test with a string to check if the string matches the regex pattern.

Therefore, from the console log, we should see that isValidZip is true since it’s a 5 digit number.

Conclusion

To validate ZIP code (US postal code) with JavaScript, we can use a regex that matches 5 digit numbers or 5 digit numbers with a 4 digit number separated by a dash.

Categories
JavaScript Answers

How to Fix the ESLint ‘Unexpected string concatenation’ Error?

Sometimes, we may run into the ‘unexpected string concatenation’ error when we’re using ESLint to lint our JavaScript project.

In this article, we’ll look at how to fix the ‘unexpected string concatenation’ error when we’re using ESLint to lint our JavaScript project.

Fix the ESLint ‘Unexpected string concatenation’ Error

To fix the ‘unexpected string concatenation’ error when we’re using ESLint to lint our JavaScript project, we should use template literals instead of string concatenation.

For instance, we write:

const ANR = 'Animal Friend,ANR,ANP,$30'
const specialityPlates = [{
  cName: 'Environmental / Wildlife',
  oSubMenu: [{
    cName: `${ANR}`,
    cReturn: `${ANR}|27.00`
  }]
}]

to interpolate the value of the ANR variable into the template string.

Therefore, cReturn is 'Animal Friend,ANR,ANP,$30|27.00'.

Conclusion

To fix the ‘unexpected string concatenation’ error when we’re using ESLint to lint our JavaScript project, we should use template literals instead of string concatenation.

Categories
JavaScript Answers

How to Get All li Elements in an Array with JavaScript?

Sometimes, we want to get all li elements in an array with JavaScript.

In this article, we’ll look at how to get all li elements in an array with JavaScript.

Get All li Elements in an Array with JavaScript

To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements.

Then we can use the spread operator to spread all the items in the node list to an array.

For instance, if we have:

<div id="navbar">
  <ul>
    <li id="navbar-One">One</li>
    <li id="navbar-Two">Two</li>
    <li id="navbar-Three">Three</li>
    <li id="navbar-Four">Four</li>
    <li id="navbar-Five">Five</li>
  </ul>
</div>

then we write:

const lis = [...document.getElementById("navbar").getElementsByTagName("li")];
console.log(lis)

to call document.getElementById("navbar") to get the div element.

Then we can select the li elements inside with .getElementsByTagName("li").

Next, we use the spread operator to spread all the returned li elements into an array an assign it to lis.

Therefore, we should see that lis is an array with the 5 li elements in the console log.

Conclusion

To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements.

Then we can use the spread operator to spread all the items in the node list to an array.

Categories
JavaScript Answers

How to Create a Dynamic Object in a Loop with JavaScript?

Sometimes, we want to create a dynamic object in a loop with JavaScript.

In this article, we’ll look at how to create a dynamic object in a loop with JavaScript.

Create a Dynamic Object in a Loop with JavaScript

To create a dynamic object in a loop with JavaScript, we can use the square bracket notation to add properties to an object dynamically.

For instance, we can write:

const objects = {};

for (let x = 0; x < 5; x++) {
  objects[x] = {
    name: 'foo'
  };
}

console.log(objects)

We create an empty object and assign it to the objects variable.

Then we add a for loop that loops through some numbers.

And we use the numbers as property names with objects[x].

Then we assign objects[x] to an object with the name property set to 'foo' as its value.

As a result, we see that the value of objects is:

{
  "0": {
    "name": "foo"
  },
  "1": {
    "name": "foo"
  },
  "2": {
    "name": "foo"
  },
  "3": {
    "name": "foo"
  },
  "4": {
    "name": "foo"
  }
}

from the console log.

Conclusion

To create a dynamic object in a loop with JavaScript, we can use the square bracket notation to add properties to an object dynamically.

Categories
JavaScript Answers

How to Convert Latitude and Longitude to Decimal Values with JavaScript?

Sometimes, we want to convert latitude and longitude to decimal values with JavaScript.

In this article, we’ll look at how to convert latitude and longitude to decimal values with JavaScript.

Convert Latitude and Longitude to Decimal Values with JavaScript

To convert latitude and longitude to decimal values with JavaScript, we can extract the numerical and directional parts of the latitude and longitude values into an array.

Then we can calculate the coordinate values from the extracted values.

For instance, we write:

const convertDMSToDD = (degrees, minutes, seconds, direction) => {
  let dd = +degrees + +minutes / 60 + +seconds / (60 * 60);
  if (direction === "S" || direction === "W") {
    dd = dd * -1;
  }
  return dd;
}

const parseDMS = (input) => {
  const parts = input.split(/[^\d\w]+/);
  const lat = convertDMSToDD(parts[0], parts[1], parts[2], parts[3]);
  const lng = convertDMSToDD(parts[4], parts[5], parts[6], parts[7]);
  return [lat, lng]
}

const coords = parseDMS(`36°57'9" N 110°4'21" W`)
console.log(coords)

to create the convertDMSToDD function that takes the degrees, minutes, seconds, and direction parameters.

Then we get the number part of the coordinates value with +degrees + +minutes / 60 + +seconds / (60 * 60) and assign the returned value to dd.

We convert number string to a number with the unary + operator.

If direction is 'S' or 'W', we multiply the dd value by -1.

And then we return dd.

Next, we create the parseDMS function with the input string.

We call split to split the string into numbers and the direction parts with /[^\d\w]+/.

Then we call convertDMSToDD with the extracted parts and return the values.

Therefore, from the console log, we see that coords is [36.9525, -110.07249999999999].

Conclusion

To convert latitude and longitude to decimal values with JavaScript, we can extract the numerical and directional parts of the latitude and longitude values into an array.

Then we can calculate the coordinate values from the extracted values.