How to remove only trailing spaces of a string in Java and keep leading spaces?
The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it? Since JDK 11 If you are on JDK 11 or higher you should probably be using stripTrailing() . Earlier JDK versions Using the regular expression \s++$ , you can replace all trailing space characters (includes space and tab characters) with the empty string ( "" ). final String text = " foo "; System.out.println(text.replaceFirst("\\s++$", "")); Output foo Online demo. Here's a breakdown of the regex: \s – any whitespace character, ++ – match one or