How to parse the javascript source for variable declarations using javascript regular expressions
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Sandip_Chitale
Posted On:   Thursday, January 9, 2003 05:03 PM

What is the best way to parse the following types of variable declarations

			
var foo;
var foo = value;
var foo, bar;
var foo, bar, baz;
var foo = value1, bar, baz = value2;


using the RegExp in javascript.

I have the following for parsing the first form -
			
var varMatcher = new RegExp("var\s+([a-zA-Z0-9_]+)\s*", "g");

Re: How to parse the javascript source for variable declarations using javascript regular expressions

Posted By:   Sandip_Chitale  
Posted On:   Saturday, January 18, 2003 11:39 AM

Well here is the code:

function dumpVars()
{
var varDeclsMatcher =
new RegExp("var\s((?:\s*(?:\w+)\s*(?:;|,|=[^,;]+[,;])\s*)+)", "g");
var oneVarMatcher =
new RegExp("\s*(\w+)\s*(?:;|,|=[^,;]+[,;])\s*", "g");

var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
if (scripts[i]) {
var scriptText = document.scripts[i].text;
if (scriptText) {
var matched;
while ((matched = varDeclsMatcher.exec(scriptText)) != null) {
var varsOnly = RegExp.$1;
var subMatched;
while ((subMatched = oneVarMatcher.exec(varsOnly)) != null) {
alert(RegExp.$1);
}
}
}
}
}
}
About | Sitemap | Contact