New Line in Textarea to be converted to <br/>
Asked Answered
N

2

34

There's a lot of threads here about converting br/> or preserving newlines across different languages, but not many regarding textarea.

I have this script:

var boxText = "";
$("textarea.BoxText").live('dblclick', function () {
    boxText = $(this).val().replace(/ /g, "<br/>");
  $(this).replaceWith( '<div class="BoxText">' + $(this).val() + '</div>' );

});
$("div.BoxText").live('dblclick', function () {
  $(this).replaceWith( '<textarea form="HTML" class="BoxText">' + boxText + '</textarea>' );
});

I have a textarea element, editable. When the user double-clicks on it, it converts into a div. However, in a div, the newlines are not preserved. I would like to convert just the new lines into
, currently, all spaces are being converted. I have a second script that converts it back to textarea, hence the variable for storing the string. I would need the
's to be reconverted into new lines as well.

This may seem redundant, but i have a good reason for this.

Nicollenicolson answered 14/5, 2011 at 4:24 Comment(0)
N
91

This will replace line breaks to HTML break tags. The different combinations are to cover the different browsers/systems and how line breaks are interpreted.

$(this).val().replace(/\r\n|\r|\n/g,"<br />")

This will bring it back to new lines - also covering how different browsers interpret innerHTML.

boxText.replace(/<br\s?\/?>/g,"\n");
Negron answered 14/5, 2011 at 4:29 Comment(7)
It does work, however, when i convert the div back to a textarea, the text disappears.Nicollenicolson
You may need to also replace < and > with the HTML entities. .replace(/</g,"&lt;").replace(/>/g,"&gt;");Negron
didn't work either, the br/> show up in the textarea, which implies that they aren't being converted to \n. jsfiddle.net/QUFZJNicollenicolson
use append() or prepend() when you want the div back to a textarea, to adding text inside div value...Portiere
Well what was happening was that the conversion of the type would occur before the string could be replaced. SO i did the replace script for the textarea after the div formation.Nicollenicolson
Awesome!! I owe you a beerDaugherty
It is better to use replaceAll() instead of replace()Polo
U
1

I don't know if this will work for you, but you can try it out

This one converts <br/> to new line in textarea

$(this).val().split("<br/>").join("\n");

And this one converts it back

boxText.split("\n").join("<br/>");

This works for me

Uropod answered 15/4, 2020 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.