Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

newline

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.

like image 990
ina Avatar asked Aug 01 '10 08:08

ina


2 Answers

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();
like image 200
Sarfraz Avatar answered Sep 30 '22 02:09

Sarfraz


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.

like image 33
darkliquid Avatar answered Sep 30 '22 01:09

darkliquid