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

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

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest