Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

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.

like image 534
Tony M Avatar asked Aug 09 '13 14:08

Tony M


People also ask

How to give br in HTML?

<br>: The Line Break element. The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

How do you put a BR tag inside a string?

The br tag in HTML starts the next element on a new line, similar to the carriage return \n in strings. Instead of using block elements for putting elements in new lines, you can use the line break tag: br . In cases like sentences, using the br tag serves as a visual line break and doesn't affect accessibility.

Why we use br tag in HTML?

Definition and Usage. The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems. The <br> tag is an empty tag which means that it has no end tag.


1 Answers

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') : "";
}
like image 133
JSager Avatar answered Sep 21 '22 12:09

JSager