How to force a line break on a Javascript concatenated string?

JavascriptConcatenation

Javascript Problem Overview


I'm sending variables to a text box as a concatenated string so I can include multiple variables in on getElementById call.

I need to specify a line break so the address is formatted properly.

document.getElementById("address_box").value = 
(title + address + address2 + address3 + address4);

I've already tried \n after the line break and after the variable. and tried changing the concatenation operator to +=.

Fixed: This problem was resolved using;

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" +  address3 +  "\n" + address4);

and changing the textbox from 'input type' to 'textarea'

Javascript Solutions


Solution 1 - Javascript

You can't have multiple lines in a text box, you need a textarea. Then it works with \n between the values.

Solution 2 - Javascript

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Solution 3 - Javascript

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

Solution 4 - Javascript

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

let title = 'John';
let address = 'address';
let address2 = 'address2222';
let address3 = 'address33333';
let address4 = 'address44444';
document.getElementById("address_box").innerText = `${title} 
${address}
${address2}
${address3} 
${address4}`;

<div id="address_box">
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionblargView Question on Stackoverflow
Solution 1 - JavascriptGuffaView Answer on Stackoverflow
Solution 2 - JavascriptjnovackView Answer on Stackoverflow
Solution 3 - JavascriptChirag Bhatia - chirag64View Answer on Stackoverflow
Solution 4 - JavascriptakhtarvahidView Answer on Stackoverflow