简体   繁体   中英

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. I tried <br /> , <br> (incorrect HTML), %0A and &#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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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