How can I convert <br> string into actual HTML <br> using jQuery?

html, jquery

Solution

Does this help?

function replaceLineBreaksWithHTML(string) {
 return string !== undefined ? string.replace(/\n/g, '<br/>') : "";
}

function replaceHTMLWithLineBreaks(string) {
 return string !== undefined ? string.replace(/<br\/>/gi, '\n') : "";
}

Problem

Maybe the question is phrased incorrectly, but here is what I'm trying to do with jQuery: Starting Point: ``` This is<br><br> some<br> <br> <br> <br> content ``` End Goal: ``` This is some content ``` Explanation: More specifically, I'm having issues working with content in a div, which then turns into a textarea on edit and then back to a div when done editing. The database has to store the < br > tags on save... it seems that textareas use newlines (\n) and returns (\r) instead so the conversion between these (< br >, \n and \r) is becoming a bit of an issue for me. Is there a proper way to handle this between multiple browsers? Perhaps it might be easier to just use textarea's the whole time (and forget about the divs)? It's when I try to move the content between a div and a textarea and then back to a div, funky things start to happen with the spacing. More Detail Edit: If the user clicks edit and turns the original div into a textarea, they start making changes and click done, but decide to cancel editing and revert to the old content instead. The textarea turns back into a div and the old content (stored in a hidden div) replaces what the user had written. Hence the back and forth of content. Edit: Great feedback, thanks all! I'd prefer not to use the whtiespace css as this needs to work on websites that have been developed already and would require edits on all of the divs holding the content on every page. < br >'s must be saved in the database.

Original source