简体   繁体   English

如何将格式化的字符串从console.log显示到html div

[英]how to display formatted String from console.log to an html div

Say I have a formatted string str written in my backend java code like this : 假设我在后端Java代码中写了一个格式化的字符串str,如下所示:

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 但是当我使用jQuery在html文件的div中显示它时,例如

$('.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. 这都是预期的,但是我想知道是否有一个实现可以将console.log显示到html标记,并且仍然保持以前的格式,而不必重新设置格式,我想我的问题是如果我有办法将console.log呈现给html。

You can either use the <pre> -tag or (recommended): You can replace every \\n in the string with <br /> . 您可以使用<pre> -tag或(推荐):您可以用<br />替换字符串中的每个\\n

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

You have to do that, because web browsers don't display normal line-breaks by themselves. 您必须这样做,因为Web浏览器本身不会显示正常的换行符。 You either have to use the <br /> -tag or a special tag like <pre> . 您必须使用<br /> -tag或特殊标签(如<pre>

Just replace \\n with <br> and put the string (wrapped into the <pre> tag) in the div as inner html. 只需将\\n替换为<br>并将字符串(包装在<pre>标记中)放入div作为内部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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM