简体   繁体   English

检测并删除javascript对象文字尾随逗号

[英]Detect and remove javascript object literal trailing commas

Trailing commas in JavaScript object literals are not accepted as a valid JavaScript syntax by IE7 : IE7不接受JavaScript对象文字中的结尾逗号作为有效的JavaScript语法:

var a = {
  foo: 12,
  bar: 13,//this is ok in all browsers except ie7
};

For the moment the way I deal with this issue is to open my website using IE7 and use the console to find the invalid js files. 目前,我处理此问题的方法是使用IE7打开我的网站,然后使用控制台查找无效的js文件。

Do you know how to locate (or even better remove) trailing commas in a javascript file using UNIX command line ? 您知道如何使用UNIX命令行在JavaScript文件中定位(甚至更好地删除)尾部逗号吗?

I tried to grep these commas but a multiline regex is needed. 我试图grep这些逗号,但需要多行正则表达式。 I also googled the subject and found nothing useful. 我也用谷歌搜索,没有发现有用的东西。

JSHint can find those for you. JSHint可以为您找到那些。 You can download it and run it from the command line. 您可以下载它并从命令行运行它。 It also has lots of useful additional things it can check for you (and options to turn the ones off that you don't want). 它还具有许多有用的其他功能,可以为您检查(以及关闭不需要的功能的选项)。

You can write a script that will do this for you: 您可以编写一个脚本来为您执行此操作:

$ cat 1.pl 
local $/;

my $data = <>;
$data =~ s@,(\s*)((?://.*?\n)?)(\s*)}@ $1$2$3}@msg;
print $data;

$ cat 1.txt 
var a = {
  foo: 12,
  bar: 13, //this is ok in all browsers except ie7
};

var b = {
  foo: 14,
  bar: 15,
};

$ perl -i 1.pl 1.txt

$ cat 1.txt 
var a = {
  foo: 12,
  bar: 13  //this is ok in all browsers except ie7
};

var b = {
  foo: 14,
  bar: 15 
};

It's not perfect but it locates files (it's not printing lines tho): 它不是完美的,但是它可以找到文件(不是在打印行):

find -name '*.js' -exec grep -Pzl ",\s*\n+(\s*\/\/.*\n)*\s*[\}\)\]]" {} \;

Answer is partially taken from this question: 答案部分取自此问题:

Regex (grep) for multi-line search needed 需要多行搜索的正则表达式(grep)

PS 聚苯乙烯

For sure there is one flaw like that: 当然,有一个缺陷是这样的:

// whatever is done next,
}

It will be reported as trailing coma, while it's not. 它将被报告为尾巴昏迷,而事实并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM