我想在文本区添加换行符。我尝试了\n和<br/>标签,但不工作。你可以看到上面的HTML代码。你能帮我在文本区插入换行符吗?

<textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>

<textarea cols='60' rows='8'>This is my statement one.<br/> This is my statement2</textarea>

当前回答

试试这个。工作原理:

<textarea id="test" cols='60' rows='8'>This is my statement one.&#10;This is my statement2</textarea>

替换<br>标签:

$("textarea#test").val(replace($("textarea#test").val(), "<br>", "&#10;")));

其他回答

使用CSS在Textarea中输入关键字行:

white-space: pre-wrap;

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p3.innerText = t.value.replace("\n", "");

<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='p3'></p>

我发现String.fromCharCode(13,10)在使用视图引擎时很有帮助。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

这将创建一个包含实际换行符的字符串,从而迫使视图引擎输出换行符而不是转义版本。使用NodeJS的EJS视图引擎-这是一个简单的例子,其中任何\n应该被替换:

viewHelper.js

exports.replaceNewline = function(input) {
    var newline = String.fromCharCode(13, 10);
    return input.replaceAll('\\n', newline);
}

EJS

<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>

呈现

<textarea>Blah
blah
blah</textarea>

replaceAll:

String.prototype.replaceAll = function (find, replace) {
    var result = this;
    do {
        var split = result.split(find);
        result = split.join(replace);
    } while (split.length > 1);
    return result;
};

一个简单自然的解决方案,不涉及CSS样式或数字字符引用,如&#13;&#10;将使用&换行符;字符实体引用:

The cardinal directions are:&NewLine;- North&NewLine;- East&NewLine;- South&NewLine;- West

注意:因为它被简单地定义为LF(换行,或U+000A Unicode码位)字符,所以不能100%确定它是否适合需要整个CR + LF(回车+换行)序列的情况。但后来,它在我在Windows 10上进行的Chrome、Edge和WebView2测试中都能运行,所以应该可以使用。

经过大量的测试,下面的代码在typescript中为我工作

 export function ReplaceNewline(input: string) {
    var newline = String.fromCharCode(13, 10);
    return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}