javascript正则表达式部分替换

时间:2016-04-19 03:13:29

标签: javascript regex

我希望将/,\s*\]/g替换为],将/,\s*\}/g替换为}。本质上我想编写一个JSON预处理来删除JSON对象或数组中的尾随逗号。但是,我写的正则表达式匹配逗号和右括号括号或结束花括号。那么我如何只删除逗号后面的任何空格,但保留右括号或大括号?

例如:

{
  "a": 1,
  "b": [1,2,3,] ,
}

预计将被替换为:

{
  "a": 1,
  "b": [1,2,3]
}

如何删除/替换前导逗号,

例如:

{
  ,"a": 1
  , "b": [,1,2,3]
}

预计将被替换为:

{
  "a": 1,
  "b": [1,2,3]
}

1 个答案:

答案 0 :(得分:0)

您可以使用look ahead之类的



var regex = /,\s*(?=[\]}])/g;

snippet.log('{a:b,}'.replace(regex, ''));
snippet.log('{a:b, }, {a:b, }'.replace(regex, ''));
snippet.log('[a:b,]'.replace(regex, ''));
snippet.log('{a: [a:b, ], a: [a:b,], }'.replace(regex, ''));

var regex2 = /(\{|\[)\s*,/g;

snippet.log('{,a:b}'.replace(regex2, '$1'));
snippet.log('{ ,a:b}, {a:b, }'.replace(regex2, '$1'));
snippet.log('[,a:b]'.replace(regex2, '$1'));
snippet.log('{ ,a: [,a:b], a: [ ,a:,b]}'.replace(regex2, '$1'));

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;