Elgs Qian Chen Elgs Qian Chen - 7 months ago 24
Javascript Question

javascript regex partial replace

I'm hoping to replace

/,\s*\]/g
to
]
and
/,\s*\}/g
to
}
. Essentially I want to write a JSON preprocess that removes tailing commas in a JSON object or array. However, the regex I wrote matches the comma and the closing bracket braces or the closing curly braces. So how I can remove only the comma optionally any white spaces following the comma, but preserve the closing bracket or curly braces?

For example:

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


is expected to be replaced to be:

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


And how about removing/replacing leading commas,

For example:

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


is expected to be replaced to be:

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

Answer

You can use look ahead like

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>

Comments