jQuery: Convert TextArea content to html string and vice versa

what I'm trying to do is converting a TextArea content into a valid html code. Suppose you type inside the TextArea and then you press a button that shows the typed text inside a element. If you typed something like inside the TextArea:

Hi folks!
Do you like jQuery?
I do!

The resulting string you have to put inside the '' element is:

Hi folks!<br>Do you like jQuery?<br>I do!

That's because the newline inside the TextArea must be converted to the <br> tag!

The same thing should happend if you want to take the html of the element and put it inside the TextArea input field, for example:

Hi folks!<br>Do you like jQuery?<br>I do!

should be converted to:

Hi folks!
Do you like jQuery?
I do!

So, is there a way to convert a string to html-string (and vice versa) or should I write a function by myself?

Thanks in advance!

1

3 Answers

With the appropriate styling on the element, you shouldn't need to convert anything. Using the CSS white-space property with a value set to pre, any white-space in the element should appear exactly as it does in the textarea:

#myElement { white-space: pre; }

Example:

2

Well, it's not very difficult:

$('#element').html($('textarea').html().replace(/\n/g, "<br />"));
4

Consider looking into a markdown editor. Stack overflow uses a modified version of this one:

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like