Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read <br> from HTML and set as \n in javascript

I have the HTML code

<span class="editableFalse" id="comments">
Lorem ipsum sit dolor amet
<br/>
Lorem ipsum sit dolor amet
</span>
<textarea id="textareaComments"></textarea>

Now I have to fetch the data from this span and set it to a Textarea below it in the same format, ie along with the newline character.

How to achieve that :

$("#textareaComments").val($("#comments").text());

The above line takes the content from the span but trims off the br tag. I dont get a newline character in the textarea. Any help.

like image 483
Learner Avatar asked Jul 08 '26 23:07

Learner


2 Answers

Just use replace:

$("#textareaComments").val($("#comments").html().replace("<br>", "\n"));
like image 119
Marcos Pérez Gude Avatar answered Jul 11 '26 11:07

Marcos Pérez Gude


var str = $("#comments").html();
var regex = /<br\s*[\/]?>/gi;
$("#textareaComments").val(str.replace(regex, "\n"));

Try the replaces Br with \n (new line) And use .html() not .text()

like image 21
Froxz Avatar answered Jul 11 '26 12:07

Froxz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!