EDIT solved
I wonder why the following code is not working-no newline is being 'produced' Anyone has an idea ? Thanks
$('#results').append("Try again! \n I believe in you");
EDIT solved
I wonder why the following code is not working-no newline is being 'produced' Anyone has an idea ? Thanks
$('#results').append("Try again! \n I believe in you");
I am assuming that you are doing an ajax call or something and the results contain the '\n' and you can't change it?
That's fine, in HTML things like \n and whitespace are ignored unless you explicitly state that you want to use the whitespace.
There are two main ways to do this.
First is with the <pre>
tag
$(function() {
$('#results').append("Try again! \n I believe in you");
})
<html>
<head>
<script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<pre id="results"></pre>
</body>
</html>
Second (better way) is with the css using white-space
In the next example I use white-space:pre-line
This will only preserve your \n or new lines
$(function() {
$('#results').append("Try again! \n I believe in you");
})
<html>
<head>
<script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div style = "white-space: pre-line" id="results"></div>
</body>
</html>
Notice that the second one is using a standard <div>
, triggers a new line and doesn't preserve the extra whitespace after the \n? That might be more of what you are looking for. You can also set it to white-space:pre
and the div should behave just like a <pre></pre>
in terms of white space and new lines.
white-space
has a lot of options:
white-space: normal|nowrap|pre|pre-line|pre-wrap|initial|inherit;
That should provide you with what you need.
You may need to use Javascript to sanitize the text if you are looking for a very specific format.
There are other ways to get breaks in text but if you are specifically using \n
then these are the only two ways that I know of to do it.
Hope this helps!
White spaces do not break in html, they collapse into a single displayed whitespace displayed as . If you want to render a break in html you have to use a break tag
<br>
$('#results').append("Try again! <br> I believe in you");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
It's in HTML, you need to use linebreaks, <br>
, instead of newlines.