简体   繁体   English

如何使用jQuery写换行符?

[英]How to write newline using jquery?

There is a formatted txt file that my java program reads and sends over the contents as a string to front-end. 我的Java程序读取并格式化了一个txt文件,并将其内容作为字符串发送给前端。 The string that is sent to front end looks like this: 发送到前端的字符串如下所示:

var result = "This is the result.\nIt contains some details\n\nDetails are as follows\nabc,xyz"

In the frontend, This data must be written to a div in the following format: 在前端,此数据必须以以下格式写入div:

This is the result.
It contains some details

Details are as follows
abc,xyz

Using the following code did not work: 使用以下代码不起作用:

$("#divId).html(result);

Alternates like val(), text() did not work either. val(),text()之类的替代项也不起作用。 How can I make the browser write the new lines in the div when displaying the result? 显示结果时,如何使浏览器在div中写入新行?

将换行符转换为<br> s

$("#divId).html(result.replace(/\n/g, "<br />"));
  $('#divId').html("<pre>" + result + "</pre>");

Use like this 这样使用

var result = "This is the result.\nIt contains some details\n\nDetails are as follows\nabc,xyz" 
var res = result.replace(/\n/g, "<br>");
$("#divId).html(res);

Let's consider a simple HTML source file. 让我们考虑一个简单的HTML源文件。

 Hello 2 new lines. 3 new lines. 

Let's consider another one: 让我们考虑另一个:

 Hello<br>The magic of HTML tags! 

You are confusing newlines with HTML <br> tags. 您将换行符与HTML <br>标记混淆了。

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

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