[英]Read <br> from HTML and set as \n in javascript
I have the HTML code 我有HTML代码
<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. 现在,我必须从该范围中获取数据,并以相同的格式(即,与换行符一起)将其设置为位于其下方的Textarea。
How to achieve that : 如何做到这一点:
$("#textareaComments").val($("#comments").text());
The above line takes the content from the span but trims off the br tag. 上一行从跨度中获取内容,但修剪了br标签。 I dont get a newline character in the textarea.
我在文本区域中没有换行符。 Any help.
任何帮助。
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()
尝试用
\\n
(新行)替换Br
并使用.html()
而不是.text()
只需使用replace:
$("#textareaComments").val($("#comments").html().replace("<br>", "\n"));
$("#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>
您还可以使用我认为的jQuery的replaceAll
$("\n").replaceAll("<br>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.