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

我怕爱的太早我们不能终老 提交于 2019-12-18 10:09:41

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/5999792/new-line-in-textarea-to-be-converted-to-br

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!