How do I remove all the <br> and turn them into line breaks (\n) in JQuery? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this questionDo I simply do a replaceWith
? What's the best way?
function replaceBreaks(s){
var content = $('<div>' + s + '</div>');
content.find("br").replaceWith("\n");
return content.html();
}
Try something like this:
$('br').text('\n').contents().unwrap();
First it adds a text node child to all br elements of \n
. Then it unwraps them leaving only the text below it. You can see it in action here:
http://jsfiddle.net/UgZNm/
I found this regex, which should take care of all kinds of formatting problems:
function br2nl(input) {
return input.replace(/<[bB][rR](\s+)?\/?>/g, "\n");
}
Parsing HTML without an actual HTML parser might be a bad idea, but regular expressions can often be Good Enough.
text.replace(/<br[^>]*>/gi, "\n");
This will replace <br>, <br/>
, <br />
, <br some_attribute="value" />
, etc etc.
However, it will not replace </br>
, in case you might have <br></br>
. If so, you could try this:
text.replace(/<\/?br[^>]*>/gi, "\n");
if you don't mind <br></br>
getting turned into \n\n.
I think replaceWith
is the best solution, as well as being clear and easy:
$(selector + ' br').replaceWith('\n');
Here's a fiddle that shows this in action: http://jsfiddle.net/hHJvM/
精彩评论