Apex String – How to Replace __c in a String

apexstring

I'm making a validator that returns an error. I'd like to show the user A good looking name like Missing Example Error instead of Missing Example_Error__c. Below is my code, yet it still prints Example_Error__c.

    for (String key : validators){
    if(!validationKeys.contains(key)){
        string newkey = key.replace('__c','').replace('_',' ');
        if(errorMap.keySet().contains('Deal')){
            errorMap.get('Deal').add('Missing '+newkey);
        }else{
            List<String> tempList = new List<String>{'Missing '+newkey};
                errorMap.put('Deal',tempList);
        }                                
    }
}

I originally had it like key = key.replace(…);
but switch to explicitly making a new string as newkey. Still isn't returning the desired result.

Am I missing something?

Best Answer

you can try to use https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_fields_describe.htm

fieldMap.get(fieldName).getDescribe().getLabel();//It provides to get the object fields label.

https://developer.salesforce.com/forums/?id=906F000000090gcIAA

and return the Label of the field

thanks