tags:

views:

241

answers:

4

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  A: 

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();
jerone
any function suggestion?
ina
problem with using replace \r\n is that on Windows systems, the \n's don't seem to get processed right
ina
No problems for me. Try the following in Firebug (or any console) on this page for example: `$("#wmd-input").val("test\r\ntest2");`
jerone
+1  A: 

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.

darkliquid
A: 

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");
});
Biggie
is `\r\n` needed or would just `\n` do?
ina
+1  A: 

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();
Sarfraz
does `/(<br>)|(<p><\/p>)/g` catch also `<br />` ?
ina
@ina: Yes updated for that too.
Sarfraz
Updated regexp for your plugin: `/(<br\s*\/?>)|(<p><\/p>)/gi`. Don't know how the `<p>` should work, is there content in there?
jerone
@jerone: Have you tried that?
Sarfraz
@sAc: Yes, you could try it here yourself: http://gskinner.com/RegExr/
jerone
@sAc: you asked for my comment: the regex is syntactically correct. The capturing group seems superfluous (i.e. you could've leave out the brackets and it'll still be correct for this case). It will not match `"<p/>"`, but that can easily be added as a fourth alternate. I don't have much experience with jQuery to comment on that part. I hesitate to upvote because I hope there's a much better way to do HTML transformation than regex.
polygenelubricants
@polygenelubricants: Thanks for your explanation, that's helpful :)
Sarfraz