Javascript 换行文本区域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8793923/
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-24 07:31:47  来源:igfitidea点击:

Javascript Line Break Textarea

javascript

提问by jcmitch

I have a text area that I want to pre-populate with some specific text that includes line breaks. I'm populating the area onLoad but I can't get the line breaks to work correctly. Any advice on how to do that? Thanks.

我有一个文本区域,我想用一些包含换行符的特定文本预先填充该区域。我正在填充 onLoad 区域,但我无法让换行符正常工作。关于如何做到这一点的任何建议?谢谢。

回答by Diodeus - James MacFarlane

You need to replace line breaks with newline characters: \n

您需要用换行符替换换行符: \n

回答by Joseph Silber

Just use the newline character: \n.

只需使用换行符:\n.

So, if you want the textarea to look like this:

所以,如果你想让 textarea 看起来像这样:

This is line 1
This is line 2

这是第 1 行
这是第 2 行

You would use a string like this:

您将使用这样的字符串:

"This is line 1\nThis is line 2";

See a demo here: http://jsfiddle.net/MzmBd/

在此处查看演示:http: //jsfiddle.net/MzmBd/

回答by Joseph Marikle

As stated multiple times, you need the \ncharacter.

正如多次所述,您需要\n角色。

see here: http://jsfiddle.net/XbALv/

见这里:http: //jsfiddle.net/XbALv/

document.getElementById("blah").value = 
"This" + "\n" +
"is some" + "\n" +
"text" + "\n";

回答by Shawn

i had tried many ways to break a textarea into an array. used this method, it might not be the best.

我尝试了很多方法将 textarea 分解为数组。使用这种方法,它可能不是最好的。

using .split('\n') does not remove the break and it will create whitespace or break when insert into database. therefore, i replace it with

使用 .split('\n') 不会删除中断,它会在插入数据库时​​创建空格或中断。因此,我将其替换为

textarea content:
12345
6789

文本区域内容:
12345
6789



a = a.replace(/\n|\r\n|\r/g, "<br>");

var stringArray = a.split('<br>');

for (var i = 0; i < stringArray.length; i++) {
var myString = stringArray[i];
myString = myString.replace('<br>', "");

response.write(myString);
}

回答by Araston

replace like this:

像这样替换:

str.replace(/[\r\n]+/g, '\\n') %>';