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

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

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


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

String s1 = 
   ' Salesforce \t     force.com ';
String s2 = 
   'Salesforce force.com', s2);

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.