Allan Macmillan
Allan Macmillan

Reputation: 1491

String with new line and tabs to display in HTML

I have a string coming from my java backend which is formatted to display in a certain way, the new line, tab and space characters are in certain positions.

How do I get this to display the same way in HTML?

For example, say I have the current string in Javascript as so:

var str = "\t\tTitle \n Some text \t\t\t more text";

Upvotes: 1

Views: 8800

Answers (4)

Nishant Jain
Nishant Jain

Reputation: 1

You can use

white-space: pre-wrap;

as it also prevents overflow

Upvotes: 0

Saqib S
Saqib S

Reputation: 541

I might be late but just in order to help if a beginner like me is facing this kind of problem.

You can add a css class to the html tag where you want to display the data. In my case I am using ngFor of Angular 2. The data coming from my back end had line breaks and tabs. So I just added a class to the html tag with a css white-spacing style as follows.

Backend Data"title": "postIssueResponse() {\n\tthis.parent.postIssueResponse(this.issueId, this.newResponse);\n console.log(this.newResponse);\n this.newResponse \u003d \"\";\n}"

<p class="response-title">{{myData?.title}}</p>

And the css

.response-title {
white-space:pre;

}

This one do the job perfectly.

Upvotes: 1

Kaushik
Kaushik

Reputation: 2090

You can use textarea also. here is a Working Fiddle

MDN textarea

Upvotes: 0

NMunro
NMunro

Reputation: 910

Browsers typically strip out extra white space, you might need to put it inside a preformatted text block or use white-space: pre

var pre = document.createElement("pre");
pre.innerHTML = str;
document.appendChild(pre);

Also yes, you need to use backslahes too, as mentioned about.

Upvotes: 6

Related Questions