7

I am trying to remove whitespace (dynamically) from an input string:

Input:  ' inputString '
Output: 'inputString'

Input:  ' Ravi kumar '
Output: 'Ravi kumar'

I want to remove the space before or after the string or both before and after, not in the middle.

I tried the following but it is removing all the spaces including middle.

inputString = inputString.replaceAll('\\s+', '');
1

2 Answers 2

20

use trim() method of String class

Returns a copy of the string that no longer contains any leading or trailing white space characters.

String s1 = '   Hello!   ';
String trimmed = s1.trim();
System.assertEquals('Hello!', trimmed);
0
19

I like using normalizeSpace() instead of trim() for such scenarios, as it also handles repeated white space.

normalizeSpace()

Returns the current String with leading, trailing, and repeating white space characters removed.

String s1 = 
   ' Salesforce \t     force.com ';
String s2 = 
   s1.normalizeSpace();
System.assertEquals(
   'Salesforce force.com', s2);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .