0

I'm trying to remove all type casts from a js file.

The current (not-working) regex I have is:

/(?!new\s+&?!function\s+)\w+\((.+)\)/gi

Basically I want anything like Class(var) but not new Class(arg) or function Func(arg)

Thanks!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

3
 s = "Basically I want anything like Class(var) but not new Class(arg) or function Func(arg)"

re = /(?:(?!new|function)\b\S+|^|[^\w\s])\s*\b([A-Z]\w*\s*\(.*?\))/g

for (var match; (match = re.exec(s));) { alert(match[1]); }

produces

 Class(var)

but will only match correctly if there are no nested parentheses in the actual parameter list. To generally match a function call is not possible using regular expressions since regular grammars can't handled nested parenthetical groups.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • I gave this the check because I think your answer answers the question I put (quite cleverly in fact), but after putting this in my script, it started changing other things that I hadn't mentioned. – Jacksonkr Jul 04 '11 at 14:54
  • @Jackson, have you looked into proper JavaScript parsers that would allow you to parse your script, walk the resulting parse tree, modify it, and then render it out? http://stackoverflow.com/questions/6511556/javascript-parser-for-java discussed this recently, and if you're not fluent in java, there are other discussion on SO for python and other languages. I believe JSLint is built around a JS parser. – Mike Samuel Jul 04 '11 at 19:45