Thursday, April 12, 2012

regular expression for matching a word

I want to get the variable names in javascript which define a string
for that I have wrote a regular expression

var x = "sdfsfsdf";

The problem with this expression is when I am using RegExp.$2 I should get the variable name as x as we consider the above code. It works fine with some expression but if there is code like

function(a) {var b = document.createElement("script");}

then the result is function(a){var b.

Please help me change my regular expression so it works in both cases.

NOTE: javascript variables can also be declared without var i.e. x = "sdfsfsf";


If your strings won't be too crazy, you can try this:



> var r = /[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi;
> 'var x = "sdfsfsdf";'.match(r);
  ["x = "sdfsfsdf";"]
> 'function(a) {var b = document.createElement("script");}'.match(r);
  ["b = document.createElement("script");"]

No comments:

Post a Comment