Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a new line in <p> tag

I try to put a new line in a <p> (html code):

<p id="text_folder"><p>

This is my jquery code:

$('#text_folder').text("first"+"\n"+"second");

But in my <p> tag the result is
first second
and not:
first
second
Anyone can help me?

like image 224
Polly Avatar asked May 26 '16 10:05

Polly


2 Answers

('#text_folder').html("first"+"<br />"+"second")

try this

like image 200
Chetan Sanghani Avatar answered Oct 11 '22 22:10

Chetan Sanghani


In HTML, all whitespace characters (including newlines) are interpreted as spaces. To put a line break in a p element, you use a br element:

$("#text_folder").html("first<br>second");

If your "first" and "second" are externally-sourced (from the user, etc.), you'll want to make sure that you deal with any special HTML characters in them first. There are a couple of ways to do that; I find replace the simplest of them:

function escapeHTML(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}

so then

var first = /*...get input from user or whatever...*/;
var second = /*...get input from user or whatever...*/;
$("#text_folder").html(escapeHTML(first) + "<br>" + escapeHTML(second));
like image 36
T.J. Crowder Avatar answered Oct 12 '22 00:10

T.J. Crowder