0

Say I have a formatted string str written in my backend java code like this :

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz       

now I managed to display it on the browser console via

console.log(str);

and when I checked it is also formatted just the way it is

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz        

but when I use Jquery to show it in a div in my html file, say for example

$('.divclass').text(str);

it will just be one line

name    : xxx       company : qweaddress : yyy       age     : asdcountry : zzz

this is all expected, but I was wondering if there is an implementation where I could possibly display the console.log to my html tag and still keep the format that I had before, instead of having to format it again, I guess my question is if there is a way to present console.log to the html in my case.

1
  • 1
    You can try the <pre> preformatted text i.e. $('.divclass').html('<pre>' + str + '</pre>'); Commented Jun 7, 2017 at 7:09

2 Answers 2

2

You can either use the <pre>-tag or (recommended): You can replace every \n in the string with <br />.

str = str.replace("\n", "<br />");

You have to do that, because web browsers don't display normal line-breaks by themselves. You either have to use the <br />-tag or a special tag like <pre>.

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

Comments

1

Just replace \n with <br> and put the string (wrapped into the <pre> tag) in the div as inner html.

var str = "name    : xxx       company : qwe\n"+
"address : yyy       age     : asd\n"+
"country : zzz    \n";

console.log(str);

str = str.replace(/\n/g, "<br>");

$(".divclass").html("<pre>"+str+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divclass">
</div>

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.