combine values of address line 1 and address line 2 javascript

How to Combine Values of Address Line 1 and Address Line 2 in Javascript

If you are building a form that requires an address, you may want to combine the values of Address Line 1 and Address Line 2 before submitting the form. This can be done easily using Javascript.

Method 1: Concatenation

The simplest way to combine the values of the two address fields is to use the concatenation operator (+).


let addressLine1 = document.getElementById("address-line-1").value;
let addressLine2 = document.getElementById("address-line-2").value;

let fullAddress = addressLine1 + " " + addressLine2;

console.log(fullAddress);

In this code, we first get the values of Address Line 1 and Address Line 2 using their respective IDs. We then concatenate the two values and store them in a new variable called fullAddress. Finally, we log the value of fullAddress to the console.

Method 2: Template Literals

Another way to combine the values of the two address fields is to use template literals.


let addressLine1 = document.getElementById("address-line-1").value;
let addressLine2 = document.getElementById("address-line-2").value;

let fullAddress = `${addressLine1} ${addressLine2}`;

console.log(fullAddress);

In this code, we use template literals to create a string that combines the values of Address Line 1 and Address Line 2. We then store this string in a new variable called fullAddress and log it to the console.

Method 3: Array Join Method

Finally, you can also use the join() method of an array to combine the values of the two address fields.


let addressArray = [
  document.getElementById("address-line-1").value,
  document.getElementById("address-line-2").value
];

let fullAddress = addressArray.join(" ");

console.log(fullAddress);

In this code, we create an array containing the values of Address Line 1 and Address Line 2. We then use the join() method to combine the values into a string separated by a space. We store this string in a new variable called fullAddress and log it to the console.

There are multiple ways to combine the values of Address Line 1 and Address Line 2 in Javascript. Choose the method that is most appropriate for your use case and implement it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe