jQuery - convert <br> and <br /> and <p /> and such to new line

泪湿孤枕 提交于 2019-12-28 13:55:31

问题


jQuery - How do you convert <br> and <br /> and <p /> and such to new line?

Does jQuery have a built in br2nl() function - this is for converting new lines tags to user-friendly textfield versions.


回答1:


You could create a function like this:

jQuery.fn.nl2br = function(){
   return this.each(function(){
     jQuery(this).val().replace(/(<br>)|(<br \/>)|(<p>)|(<\/p>)/g, "\r\n");
   });
};

And use it like any of these ways:

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



回答2:


If you want to take a chunk of html and replace
tags and self-closing tags with newline characters, doing something like:

$('#element-containing-html-to-replace').html().replace(/(<br>)|(<p><\/p>)/g, "\n");

should return a string of the container's HTML with those tags replaced with newline characters.




回答3:


You can use this code if you want to replace the html-elements itself:

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



回答4:


Not that I know of, but you can use "\r\n";

EDIT:
Credits to @sAc, but updated to actual replace the value & better regexp:

jQuery.fn.nl2br = function(){
    return this.each(function(){
        var that = jQuery(this);
        that.val(that.val().replace(/(<br\s*\/?>)|(<p><\/p>)/gi, "\r\n"));
    });
};
jQuery("textarea").nl2br();


来源:https://stackoverflow.com/questions/3381331/jquery-convert-br-and-br-and-p-and-such-to-new-line

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