How to remove few characters from a String

  • 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]}';
    

    But why is that extra comma there anyways? It's not proper JSON...

  • Jochen

    Jochen Correct answer

    5 years ago
    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]}
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used