[英]js replace \n with <br> and show
I have textarea for input and show-div to show the input: 我有用于输入的textarea和show-div以显示输入:
<textarea id="inputtext" style="height:100px"></textarea>
<button id="show">show in div</button>
<div id="showtext">
</div>
and my js: 和我的js:
$(function(){
$('#show').on('click',function(){
var text = $.trim($('#inputtext').val());
text = text.replace(/\r?\n/g, "<br />").replace(/<br\s*[\/]?>/gi, "\n");
$('#showtext').text(text);
});
});
What I want is, if you give: 我想要的是,如果您给:
a
b
c
it should also show in this form. 它也应该以这种形式显示。 but it is showing now:
abc
. 但现在显示:
abc
。
here is my fiddle: http://jsfiddle.net/5gkak/ 这是我的小提琴: http : //jsfiddle.net/5gkak/
what am I doing wrong? 我究竟做错了什么?
You need to change your fiddle to match this: http://jsfiddle.net/5gkak/1/ 您需要更改您的小提琴以使其与此匹配: http : //jsfiddle.net/5gkak/1/
$(function(){
$('#show').on('click',function(){
var text = $.trim($('#inputtext').val());
text = text.replace(/\r?\n/g, "<br />");
$('#showtext').html(text);
});
});
What you had was replacing the \\n
with <br />
and then doing the same in reverse so <br />
was getting replaced with \\n
. 您所要做的是用
<br />
替换\\n
,然后反过来做,所以<br />
被\\n
替换。 Also you needed to set the html of #showtext
. 另外,您需要设置
#showtext
的html。 Check out the difference of .text
and .html
in the jQuery docs. 在jQuery文档中查看
.text
和.html
的区别。
There are also other options (these are from the comment sections of the question): 还有其他选项(这些选项来自问题的注释部分):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.