1

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 ?

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Actually the special characters are neccesary. Basically it converts the enters and tabs, because the code is then being put into a code editor. So the markup helps display the HTML code in a nicer way, instead of everything on a single line. So I guess my question is if there's a converter that can help convert the Enters, Tabs, etc ?
0

You would need to just convert the text into JSON. Line breaks, quotes, special characters, etc., would all be escaped for you.

Use whatever language and environment you're comfortable with - pretty much any language will have a JSON serializer.

For example, in C# and ASP.NET MVC:

string html = File.ReadAllText(@"C:\myfile.html");
string json = JsonConvert.SerializeObject(html);

The variable json now can be safely injected into a webpage, and it will include the necessary quotes and special escape characters:

var someText = @Html.Raw(json);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.