Display JavaScript Source Programatically

23rd March 2009

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

  1. //<![CDATA[
  2. function displaySource(name) {
  3. $('<code>'
  4. + $('#display-' + name).prevAll('script').eq(0).html()
  5. .replace(/^\s*|\s*$/g, '')
  6. .split('\n').slice(1, -1).join('\n')
  7. .replace(/(^|\n) /g, '$1')
  8. .replace(/('[^']*')/g, '<em>$1')
  9. + '')
  10. .insertAfter('#display-' + name);
  11. }
  12. //]]>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

  1. <script type="text/javascript" id="display-test">
  2. <!--//--><![CDATA[// ><!--
  3. displaySource("test");
  4. //--><!]]>
  5. </script>

Add new comment

The content of this field is kept private and will not be shown publicly.