Display line break in <div> tag from database
I have to display an article from database inside a < div> tag. This article was inserted into database from a textarea. My problem is: i could not display exactly the structure that i inserted from the textarea (including line break)
I tried the below code to replace the enter character to < br> tag but it did not work
<div id="tmpId">${f:h(dto.accPassage)}</div>
<script>
$(function(){
$('#tmpId').html($('#tmpId').html().replace(/\n/g, '<br />'));
})
</script开发者_如何学运维>
I wonder if someone could give me some hints to solve this problem.
Thank you very much.
if you want it to be exactly as it is in the database, then just render it inside a <pre>
tag, instead of a <div>
.
<pre id="tmpId">${f:h(dto.accPassage)}</pre>
That will preserve the exact formatting in the enclosed text block.
Since you're retrieving it from the DB, why do it client-side and not do the replace as soon as you retrieve the data from your DB ? Not sure what you're using (although that's irrelevant since this can be done in any language) but in PHP, assuming $output
is your DB result it would be as easy as
$output = nl2br($output);
Hope this helps !
Use css to render /n correctly:
<span style="white-space: pre-line">Hi! next line, next line.</span>
in your case
<div id="tmpId" style="white-space: pre-line">${f:h(dto.accPassage)}</div>
Since you're using java, you could always write something like the following to replace the new lines after you've retrieved the data from database.
public static String nl2br(String s) {
return s.replaceAll("\n","<br/>");
}
// usage
nl2br("some\ntext"); //will return "some<br/>text"
Give <br>
without the ending slash.
精彩评论