+ Start a Discussion
PeacePeace 

Replace line break with comma

Hi all,

I need a simple help !!

Data in 'Billing City' and 'Shipping City' field of 'Account' object contains line breaks.

eg.  345 Shoreline Park
     Mountain View, CA 94043
     USA

 I want a code to fetch data of these two fields and and format it as below

345 Shoreline Park, Mountain View, CA 94043, USA    (ie.  in a single line and Line breaks to be replaced with comma)

 Thanks in advance !

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

Something like this should work without requiring a split or looping over the split string items...

 

String myString = '345 Shoreline Park\nMountain View, CA 94043\nUSA';
System.debug(myString);
String singleLineVersion = myString.replaceAll('\\n', ', ');
System.debug(singleLineVersion);

 

All Answers

souvik9086souvik9086

Try like this

 

List<String> strList = new List<String>();

String str = '345 Shoreline Park

                      Mountain View, CA 94043
                      USA';

strList = str.split('\n');

String finalStr;

for(String strn : strList){

if(finalStr == NULL){

finalStr = strn;

}

else{

finalStr += ',' + strn; 

}

}

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

 

Sean TanSean Tan

Something like this should work without requiring a split or looping over the split string items...

 

String myString = '345 Shoreline Park\nMountain View, CA 94043\nUSA';
System.debug(myString);
String singleLineVersion = myString.replaceAll('\\n', ', ');
System.debug(singleLineVersion);

 

This was selected as the best answer