Search code examples
javascriptjqueryhtmlmarkup

How to convert html to javascript string markup


Is there an easy way to convert HTML to a string that I can use in Javascript code, in order to insert a piece of html in a code editor?

example HTML:

<html>
    <head>
         <title>Hello World</title>
    </head>
    <body>
        <h1>Title</h1>
            <h2>Subtitle</h2>
                <p>Some text goes here</p>
    </body>
 </html>

Becomes This:

<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n

But how do I automate the process, because bigger HTML files will be hard to convert them like this by hand. Is there an easy converter available?

So in essence: Can I convert HTML code to a single line, where new lines + tabs are preserved with \n and \t ?


Solution

  • The editor that you are copying from appears to be inserting special characters for new lines and tabs.

    You could always use a minifier like this one: http://www.willpeavy.com/minifier/