简体   繁体   English

将\\ n替换为 <br> 不管用

[英]Replace \n with <br> is not working

In my mongoDB: 在我的mongoDB中:

description: "Test\n\nTest"

When I try to show it in my ejs file the text ignores de "\\n" 当我尝试在我的ejs文件中显示该文本时,文本将忽略de“ \\ n”

Test Test 测试一下

My HTML 我的HTML

<div id="description">
    <%= test.description %>
</div>

I tried to fix this using this code : 我试图使用以下代码解决此问题:

var desc = $('#description').text();
desc.replace("\n", "<br>");

$('.description').text(desc);

Also tried: 还尝试了:

desc.replace(/(?:\r\n|\r|\n)/g, '<br />');

and: 和:

desc.split("\n").join("<br />");

None of this worked 这些都不起作用

If I print var desc = $('#description').text(); 如果我打印var desc = $('#description').text(); in the Chrome console, it shows this: 在Chrome控制台中,它显示如下:

              Test

Test

What I'm doing wrong and how do i fix this? 我在做什么错,我该如何解决?

Use html() instead of text() as you want to change the HTML markup.... text() will ignore the <br> tags 要更改HTML标记,请使用html()而不是text() 。... text()将忽略<br>标记

Also you are just replacing the value not updating it.....need to put the replaced value in the desc variable by 另外,您只是替换值而不更新它.....需要将替换的值放在desc变量中

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

Also desc.replace("\\n", "<br>"); 还有desc.replace("\\n", "<br>"); will just replace the first \\n match 只会替换第一个\\n匹配项

Stack Snippet 堆栈片段

 var desc = "Test\\n\\nTest" desc = desc.replace(/\\n/g, "<br>"); $('#description').html(desc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="description"></div> 

Using your code, desc.split("\\n").join("<br />"); 使用您的代码, desc.split("\\n").join("<br />"); works fine for me. 对我来说很好。

 var desc = $('#description').text(); console.log("original text = " + desc); desc = desc.split("\\n").join("<br />"); console.log("using split/join = " + desc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="description"> Here is the contents of the div with line breaks in it. </div> 

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

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