我想在文本区添加换行符。我尝试了\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>

当前回答

我的.replace()函数使用其他答案中描述的模式无法工作。在我的案例中起作用的模式是:

var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'&#13;&#10;');

// str: "Test&#13;&#10;&#13;&#10;Test&#13;&#10;Test"

其他回答

一个简单自然的解决方案,不涉及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测试中都能运行,所以应该可以使用。

试试这个。工作原理:

<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空白属性(mdn docs),确保它被设置为一个不抑制换行的值,例如:

white-space: pre-line;

你会对这3个值感兴趣:

精准医疗 保留了空白的序列。线路只有在 源和<br>元素中的换行符。 pre-wrap 保留了空白的序列。线路断在 换行符,在<br>处,以及必要时填充行框。 行前空白序列被折叠。线路断在 换行符,在<br>处,以及必要时填充行框。

如果你使用react

函数内部

const handleChange=(e)=>{
const name = e.target.name;
let value = e.target.value;
value = value.split('\n').map(str => <span>{str}<br/></span>);
SetFileds({ ...fileds, [name]: value });
}

经过大量的测试,下面的代码在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);
}