Home > OS >  Javascript new line built string?
Javascript new line built string?

Time:05-10

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;

CodePudding user response:

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;

CodePudding user response:

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>

CodePudding user response:

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

  • Related