Learner
Learner

Reputation: 810

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.

Upvotes: 3

Views: 3099

Answers (4)

Przemek Lewandowski
Przemek Lewandowski

Reputation: 404

You can use also replaceAll from jQuery I think

$("\n").replaceAll("<br>");

Upvotes: 1

Qwertiy
Qwertiy

Reputation: 21410

$("#textareaComments").val($("#comments").clone().find("br").replaceWith("\n").end().text())
textarea {
  display: block;
  width: 100%;
  height: 10em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<textarea id="textareaComments"></textarea>

Upvotes: 1

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

Just use replace:

$("#textareaComments").val($("#comments").html().replace("<br>", "\n"));

Upvotes: 2

SergkeiM
SergkeiM

Reputation: 4168

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()

Upvotes: 2

Related Questions