function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dilyan DimitrovDilyan Dimitrov 

Apex can not remove multiple spaces in String

Hello,

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?

Regards,

Dilyan



 
KevinPKevinP
Use this Regualr Expression: /\s{1,}/ that says substrings of 1 or more spaces.
Frédéric ProvotFrédéric Provot
myString.deleteWhitespace()