1

I have a string value where I am getting the a comma with } I want to remove the last , I have tried below but it is not working.

String str = '{johny:[1,2,3,4,5],erich:[5,6,7,8,9],}';
system.debug('strValue: ' + str.Substring(str.length()-2)); 

or tried this:

system.debug('strValue: ' + str.substring(1,str.length()-1);); 

result should be like this (without comma at the end):

String str = '{johny:[1,2,3,4,5],erich:[5,6,7,8,9]}';
  • 1
    But why is that extra comma there anyways? It's not proper JSON... – sfdcfox Jun 16 '16 at 15:17
2
String str = '{johny:[1,2,3,4,5],erich:[5,6,7,8,9],}';
system.debug('strValue: ' + str.left(str.length()-2)+str.right(1));

yields

strValue: {johny:[1,2,3,4,5],erich:[5,6,7,8,9]}
5

you can use replace method of String Class

for you case use:

str.replace(',}','}');
2

If you just want to strip off the last character, this will work

String str = '{johny:[1,2,3,4,5],erich:[5,6,7,8,9],}';
system.debug('strValue: ' + str.left(str.length()-2)); 
  • this will delete the 2 characters – Nick Kahn Jun 17 '16 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.