Embed HTML Code in JavaScript File


You would like to include HTML code as a String in a JavaScript file.


Firstly, load the HTML code into a JavaScript variable (e.g. by using jQuery.ajax()).

$.ajax({url: 'http://mydomain.com/htmlfile.html'})

.done(function(html) {

Then apply the following two simple regular expressions on the html code to generate valid JavaScript code.

var safeHtml = html

.replace(/\n/g, "\\n")

.replace(/\"/g, "\\\"")

You can use this String now to build a JavaScript file:

var myScript = 'var html="'+safeHtml+'";';


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s