Converting HTML to Javascript

If you write your web page using straight HTML then the entire page content will be static. You probably have page content where you want to display different things on your page depending on the browser that your visitor is using, the time of day, randomly (eg. for banner ads), or using information passed to the page on the end of the URL or from cookies. The code that determines what your page is going to display in these instances is probably written in Javascript and you use document.write statements to actually output the selected page content.

While sticking your HTML source code inside of a document.write statement is fairly straightforward, there are a couple of things that you need to watch out for. One is that your HTML source may be broken up over several lines. You can either include each line in its own document.write statement or alternatively reorganise the code into a single line. This doesn't work where you have preformatted text (text inside <pre> tags) where you need to retain the line breaks so another solution needs to be applied to resolve this. Also a number of characters have special meanings within Javascript and we therefore need to "escape" the special meaning of these characters in order for our javascript to create the correct output. Three characters in particular can cause problems. These characters with special meanings to javascript are ' / and \. If you miss one of these in your source then you may get a Javascript error that could take quite some time to debug since these characters are not necessarily easy to spot.

To save you the trouble of having to work out all of these conversions, the following form will do them for you (and even add the rest of the document.write statement around it). Simply paste the HTML that you want to generate from Javascript into the top text box and then select the Convert button. The javascript equivalent will appear in the lower text box. Simply copy the code from there and paste it into javascript.

To show you what the above form does, I pasted the sentence These are ' / and \. into the form. The javascript that was returned reads: document.writeln('These are \' \/ and \\.'); which has the document.write statement added around the sentence as well as the problem characters being escaped from their special meanings by having a \ added to the front of them.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate