1

I am trying to remove all spaces from the following string:

howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;;     ;;; ::   :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan

and from the place where there are multiple spaces it is removed only one space and the result is:

DEBUG|domain1 howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;;    ;;;::  :::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan

So far I've tried the following:

replaceAll('\s+', '');
replaceAll('[ ]+', '');
replace(' ', '');

and few more similar expressions.

At the moment I'm using the following source code:

String domain = accountObj.Domain__c;
    System.debug('domain ' + domain);
    integer spaceInd = domain.indexOf(' ');
    System.debug('spaceInd1: ' + spaceInd);
    while (spaceInd > -1) {
        domain = domain.replace(' ', '');
        spaceInd = domain.indexOf(' ');
        System.debug('spaceInd: ' + spaceInd);
    }
    System.debug('domain1 ' + domain);

When I start the code in debug log I get the following:

USER_DEBUG|[198]|DEBUG|domain howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;;     ;;; ::   :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan
USER_DEBUG|[203]|DEBUG|spaceInd1: 75
USER_DEBUG|[207]|DEBUG|spaceInd: -1
USER_DEBUG|[209]|DEBUG|domain1 howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;;    ;;;::  :::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan

Could you please advise how to remove all spaces from the String or replace them with a single space in apex?

  • 1
    replace(' ', ''); will only replace one space, not all – cropredy Jan 21 '16 at 21:05
10

You can use normalizeSpace to remove duplicate consecutive spaces, or replaceAll:

String normalized = originalStringVar.normalizeSpace();
    -- or --
String normalized = originalStringVar.replaceAll('\\s+',' ');

Note that the double-backslash (\\) is needed to be treated as a single \ for regular expressions.

To remove all spaces, you can deleteWhitespace or replaceAll:

String nonSpaced = originalStringVar.deleteWhitespace();
    -- or --
String nonSpaced = originalStringVar.replaceAll(' ','');
| improve this answer | |

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.