jQuery - convert
and
and

and such to

2019-01-18 13:52发布

问题:

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