jQuery – 转换和以及等新行

jQuery – 你如何转换

以及

等新行?

jQuery是否具有内置的br2nl()函数 – 这是用于将新行标记转换为用户友好的文本字段版本。

你可以创建一个这样的函数:

 jQuery.fn.nl2br = function(){ return this.each(function(){ jQuery(this).val().replace(/(
)|(
)|(

)|(<\/p>)/g, "\r\n"); }); };

并像以下任何方式一样使用它:

 $(':input').nl2br(); $('textarea').nl2br(); $('#textarea_id').nl2br(); 

如果你想拿一大块html并替换
标签和带有换行符的自动关闭标签,执行以下操作:

 $('#element-containing-html-to-replace').html().replace(/(
)|(

<\/p>)/g, "\n");

应返回容器HTML的字符串,并将这些标记替换为换行符。

如果要替换html元素本身,可以使用此代码:

 $('body').find('br').replaceWith("\n"); $('body').find('p').each(function() { $(this).replaceWith("\n" + $(this).text() + "\n"); }); 

不是我所知道的,但你可以使用"\r\n" ;

编辑:
致@sAc,但更新为实际替换值和更好的正则表达式:

 jQuery.fn.nl2br = function(){ return this.each(function(){ var that = jQuery(this); that.val(that.val().replace(/()|(

<\/p>)/gi, "\r\n")); }); }; jQuery("textarea").nl2br();