jquery text(), interpret<br> as new line

Viewed 21257

Getting an element of the DOM like this

$('#id').content().text();

Problem arises with

If it gets this:

<p>Hello</p>
<p><br></p>
<p>World</p>

Naturally in Html looks like:

Hello 

World

But this jquery .text() method returns: HelloWorld

How to interpret <br> as new line? <-> How to get the text exactly as I see it in HTML?

.html() gives all the HTML tags, which I don't want. I just need the plain text with spaces, if possible.

2 Answers

If you don’t mind a destructive (“modifying the HTML code”) operation:

$("#id").find("br").replaceWith("\n").end().text()
Related