Noob_Programmer
Noob_Programmer

Reputation: 46

Javascript new line built string?

I'm building a string in JavaScript FE like you can see below, my attempt is to print some data in different rows. In my JavaScript I build the string the use getElement() and textContent to attach the string at the paragraph.

I've tried <br> <br/> \n <\r, all with no results.

var str;
str+="text" + data[0];
  str+= //Here need new line
str+="text" + data[1];

var p=document.getElementById("paragraph");
p.textContent = str;

Upvotes: 1

Views: 136

Answers (3)

Lk77
Lk77

Reputation: 2462

If you need a string that can be displayed/downloaded as a file and displayed in html at the same time, i would use \n and innerText :

var str;
str+="text" + data[0];
  str+= '\n';
str+="text" + data[1];

var p=document.getElementById("paragraph");
p.innerText = str;


the \n will be replaced by <br/> automatically when using innerText, and you wont need to style it with whitespace, and you could use the resulting string, to perhaps start a file download

Upvotes: 1

mhodges
mhodges

Reputation: 11116

A couple options you have are:

  1. put a <br/> in the string and set the p.innerHTML = str instead of setting textContent

let myEl = document.getElementById('myelement');
let data = 'test 1';
data += '<br/>';
data += 'test 2';

myEl.innerHTML = data;
<div id="myelement"></div>

OR

  1. put a \n character in the string and then use a white-space: pre in the CSS of your element

let myEl = document.getElementById('myelement');
let data = 'test 1';
data += '\n';
data += 'test 2';

myEl.textContent = data;
#myelement {
  white-space: pre;
}
<div id="myelement"></div>

Upvotes: 1

Andy
Andy

Reputation: 63524

It might be easier to use a template string, and then use innerText rather than textContent as they are different.

const arr = ['Bob', 'Jane'];

const str = `
  text: ${arr[0]}
  text: ${arr[1]}
`;

document.body.innerText = str;

Upvotes: 1

Related Questions