Steve Broom Steve Broom - 3 months ago 16
HTML Question

jQuery textarea replace carriage returns with plain text

I have an input with text that user paste in it. And I have to find all carriage returns chars and replace it with plain text "\n". "\n" should be visible in output textarea. Example

I wrote the code, but output area display my "\n" as HTML tag and make it carriage returns again. But if I use text func I can't carriage returns chars. Please help.

$("#convert").click( function () {
var txtValue = $('#input').val();
$('#output').html(txtValue.replace(/\r?\n/g, "\n"));
});


#input
and
#output
are textfields.

Answer

Just simply escape the backslash:

$('#output').html(txtValue.replace(/\n|\r/g, "\\n"));