Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-25-2010, 03:25 AM   PM User | #1
mdsy
New to the CF scene

 
Join Date: Dec 2010
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
mdsy is an unknown quantity at this point
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>
mdsy is offline   Reply With Quote
Old 12-25-2010, 03:01 PM   PM User | #2
siberia-man
Regular Coder

 
Join Date: Sep 2010
Location: Far far away
Posts: 122
Thanks: 0
Thanked 16 Times in 16 Posts
siberia-man is on a distinguished road
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?
siberia-man is offline   Reply With Quote
Old 12-25-2010, 04:45 PM   PM User | #3
mdsy
New to the CF scene

 
Join Date: Dec 2010
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
mdsy is an unknown quantity at this point
Quote:
Originally Posted by siberia-man View Post
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)
mdsy is offline   Reply With Quote
Old 12-26-2010, 10:35 PM   PM User | #4
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,468
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Code:
vbsTojs(' msgbox "hello world!" ')
didn't work for me, says something about matching "Function"...
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 12-27-2010, 12:47 PM   PM User | #5
mdsy
New to the CF scene

 
Join Date: Dec 2010
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
mdsy is an unknown quantity at this point
Quote:
Originally Posted by rnd me View Post
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,....
mdsy is offline   Reply With Quote
Old 12-29-2010, 03:25 AM   PM User | #6
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,468
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by mdsy View Post
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");}
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 12-31-2010, 06:39 AM   PM User | #7
mdsy
New to the CF scene

 
Join Date: Dec 2010
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
mdsy is an unknown quantity at this point
Quote:
Originally Posted by rnd me View Post
i'll look again to see if i can find my big stash
are we talking about code or dope ;-)
mdsy is offline   Reply With Quote
Reply

Bookmarks

Tags
convert, jscript, regular expression, vbscript

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:01 PM.


Advertisement
Log in to turn off these ads.