Quick and dirty text based hack in TXR:
script.txr:
@(collect)
@prolog
@(last)
<script>
@(end)
@(collect :vars (code))
@ (block occurs)
@ (cases)
@{decl /(var )?/}@{var /[a-z]+/}=@expr
@ (trailer)
@ (skip)
@ (cases)
@ (skip)@var@(skip)
@ (bind code `@decl@var=@expr`)
@ (or)
</script>
@ (fail occurs)
@ (end)
@ (or)
@code
@ (end)
@ (end)
@(last)
</script>
@(end)
@(collect)
@epilog
@(end)
@(output)
@{prolog "\n"}
<script>
@{code "\n"}
</script>
@{epilog "\n"}
@(end)
Test case script.html:
verbatim
text
<script>
a={name:"abc"};
b={xyz:"123"};
this.c='aaa';
this.cc='bbb';
d=new Date();
var e=new Array();
var f=false;
this.g=123;
this.g++;
</script>
left
alone
Run:
$ txr script.txr script.html
verbatim
text
<script>
a={name:"abc"};
b={xyz:"123"};
this.c='aaa';
this.cc='bbb';
var e=new Array();
this.g=123;
this.g++;
</script>
left
alone
As you can see, some condensing was achieved.
Howver, the code thinks that aaa constitutes a use of the variable a. The variable e is retained because e occurs in var f=false; but you don't see that any more because that line itself is deleted since f does not occur.
If you want more than dumb text based hacks, you have to parse the Javascript. (Possible in a clear and disciplined grammar-based way in TXR also, but coding all the grammar rules is tedious.)