Javascript 使用javascript字符串换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4558008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:56:30  来源:igfitidea点击:

line breaks using javascript strings

javascriptstringline-breaks

提问by Pradyut Bhattacharya

I m breaking a line in javascript using \n for example: -

我正在使用 \n 在 javascript 中换行,例如:-

text = "this is a test" + "\n" + "another test";

text = "这是一个测试" + "\n" + "另一个测试";

and to show that in html i m using the code

并使用代码在 html 中显示

text = text.replace('\n' , '<br>');

but the text i m getting is without the br

但我得到的文字没有 br

when checking in firebug console i get is with line break(\n not shown but newline created)

在检查萤火虫控制台时,我得到的是换行符(\n 未显示,但已创建换行符)

how can i place line breaks using \n or i have to do some custom code instead of \n

我如何使用 \n 放置换行符,或者我必须执行一些自定义代码而不是 \n

thanks

谢谢

采纳答案by Babiker

var newText = text.replace(/\n/g , "<br>");

回答by jondavidjohn

use double quotes to not escape the \n

使用双引号不转义 \n

try this:

尝试这个:

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

回答by Terrorist

/\r\n|[\r\n]/g <- this is what I use. I am a pessimist..

/\r\n|[\r\n]/g <- 这是我使用的。我是一个悲观主义者。。