Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / XML

JavaScript Formatter Tool

Rate me:
Please Sign up or sign in to vote.
2.71/5 (14 votes)
28 Jan 20043 min read 127.5K   25   9
Building an App to format JavaScript for use in code behind / custom web controls

Introduction

A little while ago, I set myself the task of building a web datepicker control. I did some research, and got hold of some JavaScript code that would be perfect for the control. Now I had to rewrite the JavaScript line by line so that I could render it to the browser from within my control. And the script was over 600 lines long. As you can imagine, manually rewriting this code would not only take forever, but the chances of making syntax errors are high, especially as it's all being stored in a string (no highlighting of syntax errors in VS.NET). I've gone through this before, and wasn't about to attempt it again.

What I needed was a quick and easy way to reformat the JavaScript into a render method that I could call from within my code. With all the controls I'm building lately, this is becoming a repetitive task, so a reusable solution would be nice. I looked around, but couldn't find any existing downloadable software that would do the job, so I decided to build my own.

Background

I started out in .NET as a VB programmer, having moved over from ASP to ASP.NET about a year ago. Well development teams change, and a month ago, I found myself being the only VB guy left, and quickly made the move to C# (before I became extinct around here). I still do some maintenance on existing apps, and knew that this software would also come in useful there too, so I needed to build it to generate code in both languages (VB.NET & C#). At the same time, I could get in some more practice in my new language of choice, and start getting used to how string manipulation is handled in C#.

Using the Application

You can simply run the executable to use the app. Paste your JavaScript into the script block at the top, select the language you wish to generate the code in, and click the "Create Code" button. The code is generated in the bottom block, and can be copied from there and pasted directly into your code.

Slight Modifications You May Want to Make

In my haste while building the control, I didn't think to use the StringBuilder Class in the generated code, and am instead just building up a string. Should you want to change this (to do things properly), edit the attached source code (in file convert.cs) to render a stringbuilder instead of a string.

About the Code

The code for this project is actually quite simple, and really only needs basic understanding of both VB.NET & C# syntax. The code simply reads from the textbox, and line by line wraps it in C# or VB code, replacing all the necessary characters for the language it's to be rendered to.

There are two methods in the Convert Class, ToC (converts to C#) and ToVB (converts to VB). C# uses a \ as the escape character, followed by an escape character reference. So I first needed to replace all \'s with \\. I also needed to sort out the "s, so I had to replace \" with \\\", and then of course, I needed to wrap everything up to be formatted as a string.

C#
public string toC(string strInput) 
    {
      string strOutput = "";
      string strTemp = "";
      System.Array arrSplitString = strInput.Split('\n');
      strOutput += "private void placeJavascript()" + 
          "\n" + "{" + "\n";
      strOutput += "string strBuildUp = " + 
          "\"<script language=JavaScript>\"" + ";" + "\n";
      foreach (string strItem in arrSplitString) 
      {
        if (strItem.Length > 0) 
        {
          strTemp = strItem.Replace("\r","");
          strTemp = strTemp.Replace("\\","\\\\");
          strTemp = strTemp.Replace("\"","\\\"").Trim();

          strOutput += "strBuildUp += \"" + strTemp + "\"" 
             + " + \"\\n\"" + ";" + "\n";  
        }
      }
      strOutput += "strBuildUp += \">\"" + ";" + "\n";
      strOutput += "strBuildUp += \"/\"" + ";" + "\n";
      strOutput += "strBuildUp += \"script>\"" + ";" + "\n";
      strOutput += 
  "if(!System.Web.UI.Page.IsClientScriptBlockRegistered(\"clientScript\")){" 
        + "\n";
      strOutput += 
  "System.Web.UI.Page.RegisterClientScriptBlock(\"clientScript\"," +
       " strBuildUp);"
        + "\n";
      strOutput += "}" + "\n";
      strOutput += "}" + "\n";
      return (string) strOutput;
    }

The VB Code generation is pretty much the same. I needed to replace " with "", so from my app code, I had to replace \" with \"\", and so on and so on. Both outputs needed code to register the JavaScript client side, so there is a check built in to see if the code had already been registered, and if not, register my output.

C#
public string toVB(string strInput)
    {
      string strOutput = "";
      string strTemp = "";
      System.Array arrSplitString = strInput.Split('\n');
      strOutput += "private Sub placeJavascript()" + "\n";
      strOutput += "Dim strBuildUp As String = " + 
             "\"<script language=JavaScript>\"" + "\n";
      foreach (string strItem in arrSplitString) 
      {
        if (strItem.Length > 0) 
        {
          strTemp = strItem.Replace("\r","");
          strTemp = strTemp.Replace("\"","\"\"").Trim();
          strOutput += "strBuildUp += \"" + strTemp + "\"" 
               + " & chr(13) " + "\n";  
        }
      }
      strOutput += "strBuildUp += \"<\"" + "\n";
      strOutput += "strBuildUp += \"/\"" + "\n";
      strOutput += "strBuildUp += \"script>\"" + "\n";
      strOutput += 
        "If Not (System.Web.UI.Page.IsClientScriptBlockRegistered" +
        "(\"clientScript\")) Then " + "\n";
      strOutput += "System.Web.UI.Page.RegisterClientScriptBlock" + 
            "(\"clientScript\", strBuildUp)" + "\n";
      strOutput += "End If" + "\n";
      strOutput += "End Sub" + "\n";
      return (string) strOutput;
    }

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


Written By
Web Developer
South Africa South Africa
Doug is an Applications Integrator for an online gaming company. He has been programming for 9 years, and has been working with the .NET framework since the beginning of 2003, in both VB.NET & C#.

Comments and Discussions

 
GeneralMy vote of 5 Pin
LeonardoFiorot4-May-13 7:10
LeonardoFiorot4-May-13 7:10 
QuestionWhy? Pin
freema19-Aug-06 4:56
freema19-Aug-06 4:56 
GeneralSomething easier Pin
dadgad21-Jul-06 10:52
dadgad21-Jul-06 10:52 
GeneralNice one Pin
camacodeproject24-Jan-06 15:20
camacodeproject24-Jan-06 15:20 
Generaldll absent Pin
Sync1100p18-Oct-04 4:52
Sync1100p18-Oct-04 4:52 
GeneralStringBuilder is better Pin
Yauhen Safrankou29-Jan-04 1:50
Yauhen Safrankou29-Jan-04 1:50 
IMHO, subj
GeneralRe: StringBuilder is better Pin
Doug Wilson29-Jan-04 2:16
Doug Wilson29-Jan-04 2:16 
GeneralRe: StringBuilder is better Pin
Yauhen Safrankou29-Jan-04 2:24
Yauhen Safrankou29-Jan-04 2:24 
GeneralRe: StringBuilder is better Pin
Doug Wilson29-Jan-04 2:32
Doug Wilson29-Jan-04 2:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.