[SalesForce] Replacing white spaces is not working – replaceAll(‘\\s+’

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');

Best Answer

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+', '-');
Related Topic