Reputation: 115
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 ?
Upvotes: 1
Views: 1213
Reputation: 40393
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);
Upvotes: 0
Reputation: 1211
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/
Upvotes: 3