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
  • 1
    But why is that extra comma there anyways? It's not proper JSON...
    – sfdcfox
    Jun 16, 2016 at 15:17

3 Answers 3

3
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)); 
1
  • 2
    this will delete the 2 characters
    – Nick
    Jun 17, 2016 at 16:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .