简体   繁体   English

换行符不适用于textarea替换

[英]Newline does not work on textarea replace

I'm trying to replace a word in a textarea with another text, but I cannot seem to get newlines to work. 我正在尝试将文本区域中的一个单词替换为另一个文本,但是我似乎无法使用换行符。

<input type="text" id="testing" value="Newline \n test" /><br />
<textarea>test</textarea><br />
<button>Test</button>

$("button").on("click", function() {
    $("textarea").text($("textarea").text().replace(/test/g, $("#testing").val()));
});

Press the button. 按下按钮。 It will not replace the \\n with a new line. 不会用新行替换\\ n。 I tried <br /> , <br> (incorrect HTML), %0A and &#13;&#10; 我尝试了<br /><br> (错误的HTML), %0A&#13;&#10; but it still does not work. 但它仍然不起作用。

Fiddle 小提琴

You need to replace the character string '\\n' (2 characters '\\','n') with the actual \\n line break character. 您需要用实际的\\ n换行符替换字符串'\\ n'(2个字符'\\','n')。

This should do what you need. 这应该做您需要的。

var textBoxline = $("#testing").val().replace(/\\n/g, '\n');                                
$("textarea").text($("textarea").text().replace(/test/g, textBoxline));

You will still need to make allowances for leading/trailing spaces around the \\n itself. 您仍然需要为\\ n本身周围的前导/尾随空格留出余地。

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

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