javascript regex partial replace -


i'm hoping replace /,\s*\]/g ] , /,\s*\}/g }. want write json preprocess removes tailing commas in json object or array. however, regex wrote matches comma , closing bracket braces or closing curly braces. how can remove comma optionally white spaces following comma, preserve closing bracket or curly braces?

for example:

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

is expected replaced be:

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

and how removing/replacing leading commas,

for example:

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

is expected replaced be:

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

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 `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->  <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -