1

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;

1
  • In html use <br /> tag for a visual new line. For a file on filesystem "\n" works generally. Commented May 9, 2022 at 14:05

3 Answers 3

1

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;

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.