CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a JavaScript (http://www.codingforums.com/forumdisplay.php?f=19)
-   -   VBScript to Javascript Converter (http://www.codingforums.com/showthread.php?t=213116)

mdsy 12-25-2010 03:25 AM

VBScript to Javascript Converter
 
This is a a VBScript to Javascript converter I cooked up in a couple of hours, it uses regular expressions for searching and replacing, only converts (some of the) syntax not the functions...
I needed this for myself, and thought to share it, the code is a mess so don't be so hard on me ;-)
Only tested in firefox...

Code:

var strs=[];

function vbsTojs(vbs){

       
        var s = vbs;
       
        s = HideStrings(s);
       
    //only function block
    s = s.match(/Function[\w\W]+End\s+Function/gim)[0];

        //line-continuation char
        s = s.replace(/_\n/gm,"");

    //replace ":" with CRLF
    s = s.replace(/:/gm,"\n");

    //move inline comment to its own line
    s = s.replace(/^(.+)'(.*)$/gim,"'$2\n$1");

    //single line if -> multiple line
    s = s.replace(/\bthen\b[ \t](.+)/gi,"then\n$1\nEnd If");

    //alert(s);
   
        var Vars='';
        var Fx='';
        var FxHead='';
        var Args = '';
       
        a=s.split('\n');
       
        //trim
        for(i=0;i<a.length;i++){
                a[i]=a[i].replace(/^\s+|\s+$/,"");
        }
        //remove empty items
        a=a.filter(function(val) { return val !== ""; });

   
    //alert(a.join('\n'));
       
       
        //function
        a[0]=a[0].replace(/function\s+/i,"");
        Fx = a[0].match(/^\w+/)[0];
        a[0]=a[0].replace(Fx,"").replace(/[\(\)]/g,"");
        a[0]=a[0].replace(/\bbyval\b/gi,"").replace(/\bbyref\b/gi,"").replace(/\boptional\b/gi,"");
        a[0]=a[0].replace(/\bas\s+\w+\b/gi,"");
        a[0]=a[0].replace(/\s+/g,"");
        a[0]=a[0].replace(/,/gi,", ");
        FxHead = "function " + Fx+ " ("+ a[0] + "){";
        a[0]="";
       
        //end function
        a.length = a.length-1;
       
        for(i=1;i<a.length;i++){
       
                //Vars
                if(a[i].search(/^dim\s+/i)>-1){
                        a[i]=a[i].replace(/dim\s*/i,"");
                        Vars += a[i] + ",";
                        a[i]='';
               
                //FOR
                }else if(a[i].search(/^\bFOR\b\s+/i)>-1){
                        a[i]=a[i].replace(/^\bFOR\b\s+/i,"");
                        counter = a[i].match(/^\w+/)[0];
                        from = a[i].match(/=\s*[\w\(\)]+/)[0];
                        from=from.replace(/=/,"").replace(/\s+/g,"");
                        a[i]=a[i].replace(counter,"").replace(from,"").replace(/\bTO\b/i,"");
                        to = a[i].match(/\s*[\w\(\)]+\s*/)[0];
                        to=to.replace(/=/,"").replace(/\s+/g,"");
                        a[i] = "for(" + counter + "=" + from + "; " + counter + "<=" + to + "; " + counter + "++){"
       
                //NEXT
                }else if(a[i].search(/^NEXT\b/i)>-1){
                        a[i] = "}";
                //EXIT FOR
                }else if(a[i].search(/\bEXIT\b\s*\bFOR\b/i)>-1){
                        a[i] = "break";
       
                //IF
                }else if(a[i].search(/^\bIF\b\s+/i)>-1){
                        a[i]=a[i].replace(/^\bIF\b\s+/i,"");
                        a[i]=a[i].replace(/\bTHEN$\b/i,"");
                        a[i]=a[i].replace(/=/g,"==").replace(/<>/g,"!=");                //TODO: it should not replace if inside a string! <---------------
                        a[i]=a[i].replace(/\bOR\b/gi,"||").replace(/\bAND\b/gi,"&&");    //TODO: it should not replace if inside a string! <---------------
                        a[i] = "if(" + a[i] + "){";
       
                //ELSE
                }else if(a[i].search(/^ELSE/i)>-1){
                        a[i] = "}else{";

                //END IF
                }else if(a[i].search(/^END\s*IF/i)>-1){
                        a[i] = "}";

                //WHILE
                }else if(a[i].search(/^WHILE\s/i)>-1){
                        a[i] = a[i].replace(/^WHILE(.+)/i,"while($1){");
                //WEND
                }else if(a[i].search(/^WEND/i)>-1){
                        a[i] = "}";

                //DO WHILE
                }else if(a[i].search(/^DO\s+WHILE\s/i)>-1){
                        a[i] = a[i].replace(/^DO\s+WHILE(.+)/i,"while($1){");
                //LOOP
                }else if(a[i].search(/^LOOP$/i)>-1){
                        a[i] = "}";

                //EXIT FUNCTION
                }else if(a[i].search(/\bEXIT\b\s*\bFUNCTION\b/i)>-1){
                        a[i] = "return";

        //SELECT CASE
        }else if(a[i].search(/^SELECT\s+CASE(.+$)/i)>-1){
            a[i]=a[i].replace(/^SELECT\s+CASE(.+$)/i,"switch($1){");
        }else if(a[i].search(/^END\s+SELECT/i)>-1){
            a[i] = "}";
                }else if(a[i].search(/^CASE\s+ELSE/i)>-1){
                        a[i] = "default:";
        }else if(a[i].search(/^CASE[\w\W]+$/i)>-1){
            a[i] = a[i] + ":" ;
        }
                //CONST
                else if(a[i].search(/^CONST/i)>-1){
                        a[i] = a[i].replace(/^CONST/i,"const");
                }
               
                else{
            //alert(a[i]);
                }
               
                //COMMENT
                if(a[i].search(/^\'/)>-1){
            a[i]=a[i].replace(/^\'/,"//");
                }else if(a[i].search(/\'.*$/)>-1){
            a[i]=a[i].replace(/\'(.*)$/,"//$1");
        }
        }
       
    //alert(a.join("*"));       
       
        Vars = Vars.replace(/\s*AS\s+\w+\s*/gi,"");
        if(Vars!="") Vars = "var " + Vars.replace(/,$/,";").replace(/,/g,", ");
        FxHead  + '\n' + Vars;
       
        a=a.filter(function(val) { return val !== ""; }) //remove empty items
       
        for(i=0;i<a.length;i++){
                if (a[i].search(/[^}{:]$/)>-1) a[i]+=";";
        }
       
        ss = FxHead + '\n' + Vars + '\n' + a.join('\n') + '\n}';
       
        ss = ss.replace(new RegExp(Fx+"\\s*=\\s*","gi"),"return ");
       
        ss = UnHideStrings(ss);

        return jsIndenter(ss);
}




//-----------------------------------------------------

function jsIndenter(js){

    var a=js.split('\n');
        var margin=0;
        var s = '';

        //trim
        for(i=0;i<a.length;i++){ a[i]=a[i].replace(/^\s+|\s+$/,""); }
        //remove empty items
        a=a.filter(function(val) { return val !== ""; });


        for(var i=1;i<a.length;i++){

                if(a[i-1].indexOf("{")>-1) margin += 4 ;
     
        if(a[i].indexOf("}")>-1) { margin -= 4; }
       
                if(margin<0) margin = 0;

                a[i] = StrFill(margin," ") + a[i] ;
        }
        return a.join('\n');
}


function StrFill(Count,StrToFill){
        var objStr,idx;
        if(StrToFill=="" || Count==0){
                return "";
        }
        objStr="";
        for(idx=1;idx<=Count;idx++){
                objStr += StrToFill;
        }
        return objStr;
}

function HideStrings(text){

    const x = String.fromCharCode(7);
    const xxx = String.fromCharCode(8);

    text = text.replace(/"""/gim, '"'+xxx);  //hide 3 quotes " " "
    var idx=0, f=0;
    while(f>-1){
        f = text.search(/".+?"/gim);
        if(f>-1){
            strs.push(text.match(/".+?"/)[0]);
            //alert(strs[idx]);
            text = text.replace(/".+?"/, x+idx+x);
            idx++;
        }
    }
    //alert(text);
    return text;
}

function UnHideStrings(text){
    for(var i=0; i<strs.length; i++){
        text = text.replace(new RegExp("\\x07"+i+"\\x07"), strs[i]);
    }
    //Unhide 3 quotes " " " ***BUG: causes unterminated string if triple-quotes are at the end of the string
    text = text.replace(/\x08/gim,'\\"');
    text = text.replace(/""/gi,'\\"');   
    return text;
}

and here is a HTML test page:


Code:

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<title>vbs-to-js</title>

<script type="text/javascript" src="vbs to js.js"></script>
<script type="text/javascript" src="jbeauty.js"></script>
<script type="text/javascript" src="test.js"></script>

</head>

<body>
<center>

        <p><textarea rows="16" id="vbs" cols="110"></textarea>
<br>
        <textarea rows="16" id="js" cols="110"></textarea></p>
        <p>&nbsp;</p>
        <p><input type="button" value="Convert" id="btn"></p>
    <p><input type="button" value="Beautify" id="btn2"></p>       
        <p><input type="button" value="test" id="btn3"></p>       
</center>


<script type="text/javascript">
btn=document.getElementById("btn");
btn2=document.getElementById("btn2");
vbs=document.getElementById("vbs");
js=document.getElementById("js");
function doIt(){
        js.value = vbsTojs(vbs.value)
}
function doTest(){
        js.value = test(vbs.value)
}
btn.onclick = doIt;
btn2.onclick = beauty2;
btn3.onclick = doTest;

</script>

</body>

</html>


siberia-man 12-25-2010 03:01 PM

Quote:

<script type="text/javascript" src="vbs to js.js"></script>
<script type="text/javascript" src="jbeauty.js"></script>
<script type="text/javascript" src="test.js"></script>
There are three external scripts. Hope that "vbs to js.js" is posted above. Where are others? Do we need all of them?

mdsy 12-25-2010 04:45 PM

Quote:

Originally Posted by siberia-man (Post 1031837)
There are three external scripts. Hope that "vbs to js.js" is posted above. Where are others? Do we need all of them?

Yes, "vbs to js.js" is posted above.

sorry for the confusion...they are not needed! (I used them for testing only)

rnd me 12-26-2010 10:35 PM

Code:

vbsTojs(' msgbox "hello world!" ')
didn't work for me, says something about matching "Function"...

mdsy 12-27-2010 12:47 PM

Quote:

Originally Posted by rnd me (Post 1032054)
Code:

vbsTojs(' msgbox "hello world!" ')
didn't work for me, says something about matching "Function"...

You need to pass it a complete function:
Code:

Public Function CountWords(ByVal Text As String) As Long
'Original Function Source:  VB-World

'Assume a hyphen at the end of a line is part of a full-word, so combine together
Text = Trim$(Replace$(Text, "-" & vbNewLine, ""))

'Replace new lines with a single space
Text = Trim$(Replace$(Text, vbNewLine, " "))

'Replace Tab with Space    '//Me'
Text = Trim$(Replace$(Text, vbTab, " "))

'Collapse multiple spaces into one single space
Do While Text Like "*  *"
    Text = Replace$(Text, "  ", " ")
Loop

'Split the string and return counted words
CountWords = 1 + UBound(Split(Text, " "))
   
End Function

and it will give you:
Code:

function CountWords (Text){
    //Original Function Source;
    VB-World;
    //Assume a hyphen at the end of a line is part of a full-word, so combine together;
    Text = Trim$(Replace$(Text, "-" & vbNewLine, \"));
    //Replace new lines with a single space;
    Text = Trim$(Replace$(Text, vbNewLine, " "));
    //;
    //Replace Tab with Space    '//Me;
    Text = Trim$(Replace$(Text, vbTab, " "));
    //Collapse multiple spaces into one single space;
    while( Text Like "*  *"){
        Text = Replace$(Text, "  ", " ");
    }
    //Split the string and return counted words;
    return 1 + UBound(Split(Text, " "));
}

notice also that currently it does not convert built-in functions, might add that later.
it converts syntax: If Then Else, Select Case, While,....

rnd me 12-29-2010 03:25 AM

Quote:

Originally Posted by mdsy (Post 1032189)
notice also that currently it does not convert built-in functions, might add that later.
it converts syntax: If Then Else, Select Case, While,....

this will get you started. i thought i had almost all of them somewhere. i'll look again to see if i can find my big stash.

Code:

function mid(st, b, n)                { return st.substr(b, n)};  //like vb's mid(str, begin, #chars)
function left(st, n)                { return st.substring(0, n)};        //like vb's left(str, #chars)
function right(st, n)                { return st.substring(st.length-n)};        //like vb's right(str, #chars)
function instr(st, mat)                {return st.indexOf(mat)}
function instrrev(st, mat)        {return st.lastIndexOf(mat)}
function lcase(st)                {return st.toString().toLowerCase()}
function replace(st, fnd, rep)        {try{return st.replace( fnd, rep)}catch(rr){return} ;}
function cstr()                {return arguments[0].toString()}
function val()                {return parseFloat(arguments[0])}
function cint()                {return parseInt(arguments[0])}
function rnd()                {return Math.random()}
function Rnd(w)                {return parseInt(Math.random()*(w+1))}
function string$(s, n) {var b = [];for (var z = 0; z < n; z++) {b[z] = s;}return b.join("");}
function LTrim(value) {var re = /\s*((\S+\s*)*)/;return value.replace(re, "$1");}
function RTrim(value) {var re = /((\s*\S+)*)\s*/;return value.replace(re, "$1");}
function trim(st) {return st.replace(/^\W+(\w.+\w)\W+$/m, "$1");}


mdsy 12-31-2010 06:39 AM

Quote:

Originally Posted by rnd me (Post 1032963)
i'll look again to see if i can find my big stash

are we talking about code or dope ;-)


All times are GMT +1. The time now is 11:25 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.