0

我想在 javascript 中获取变量名,它为我写了一个正则表达式定义了一个字符串

var x = "sdfsfsdf";

((\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)

这个表达式的问题是,当我使用上面的代码时,RegExp.$2我应该得到变量名。x它适用于某些表达式,但如果有类似的代码

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

那么结果是function(a){var b

请帮助我更改我的正则表达式,使其适用于两种情况。

注意:javascript 变量也可以在没有varie的情况下声明x = "sdfsfsf";

4

3 回答 3

0
/(^|;|{)\s*(var\s+)?(\S+)\s*=\s*['"][^'"]*['"]\s*(}|;|$)/i

(^|;|{)          at the beginning, after a semicolon or the bracket
\s*              0-n whitespace characters
(var\s+)?        could be followed by "var" with at least one whitespace
(\S+)            at least one none whitespace character
\s*=\s*          equal sign with possibly surrounded whitespaces
['"][^'"]*['"]   a 'string'
\s*(}|;|$)       have to end with the bracket or a semicolon or the end of the variable has been reached

另请参阅此示例

于 2012-04-10T06:19:57.470 回答
0

如果你的琴弦不会太疯狂,你可以试试这个:

/[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi

测试:

> var r = /[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi;
  undefined
> 'var x = "sdfsfsdf";'.match(r);
  ["x = "sdfsfsdf";"]
> 'function(a) {var b = document.createElement("script");}'.match(r);
  ["b = document.createElement("script");"]
于 2012-04-10T05:57:07.303 回答
-1

试试这个正则表达式:([^\w]?(\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)

于 2012-04-10T05:46:14.047 回答