Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Line in Textarea to be converted to <br/>

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.

like image 331
C_K Avatar asked May 14 '11 04:05

C_K


People also ask

How do you make a new line in textarea?

\n is the linefeed character literal (ASCII 10) in a Javascript string. <br/> is a line break in HTML.

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How do you add a new line character in HTML?

To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags. Each <br> tag you enter creates another blank line.


1 Answers

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"); 
like image 163
Neil Avatar answered Sep 28 '22 18:09

Neil