4

I have a string where I want to replace all of the spaces with plus (+) symbols.

I've tried a number of different ways but the debug log is always showing that nothing is being replaced

I'm passing in a = 101 e wilson st c = madison z = 53703

the end result should be: 101+e+wilson+st+madison+53703

However it's coming out as: 101 e wilson st+madison+53703

string param = a + '+' + c + '+' + z; So the replace all Regex is not working.

Apex:

  public void getCoord(string a, string c, string z){
            Http h = new Http();
            HttpRequest req = new HttpRequest();

            a.replaceAll('\\s+', '-');
            c.replaceAll('\\s+', '-');
            z.replaceAll('\\s+', '-');

            string param = a + '+' + c + '+' + z;
            system.debug('looking for coordinates');
            req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+ param +'&sensor=false');
10

The replaceAll method returns the modified string, it does not modify the reference to the value passed.

So you should change it to this and it should work for you:

a = a.replaceAll('\\s+', '-');
c = c.replaceAll('\\s+', '-');
z = z.replaceAll('\\s+', '-');
  • this worked perfect – tjcinnamon Aug 1 '16 at 16:30
6

Eric has a good answer, but this will also work for this specific case, just a generic method for what you're trying to do, this will return a working format for POST to google

public static String buildAddressForGooglePost(String street, String city, String state, String postalCode, String country)
{
    String result = '';

    if (street != null) result += street +', ';
    if (city != null) result += city +', ';
    if (state != null) result += state +' ';
    if (postalCode != null) result += postalCode +', ';
    if (country != null) result += country;

    result = EncodingUtil.urlEncode(result, 'UTF-8');

    return result;
}
  • 2
    You could also just do a List<String> with a , join. Bit cleaner IMO. – Adrian Larson Jul 29 '16 at 4:17
  • Yup for sure, I agree.. – EricSSH Jul 29 '16 at 4:59
  • @AdrianLarson how would I do that? – tjcinnamon Jul 29 '16 at 21:22

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.