Skip to content
Advertisement

Remove every space EXCEPT leading spaces

I need to remove every spaces from a String EXCEPT leading spaces.

I have some strings that look like this :

JavaScript

And I am trying to achieve this :

JavaScript

That’s like a reverse trim().

What’s the most efficient way to go about it ?

Advertisement

Answer

You can use replaceAll with this regex (?<=S)(s+)(?=S) like this :

JavaScript

Examples of input & outputs:

JavaScript

The first regex keep only leading and trailing spaces, if you want to keep only the leading spaces, then you can use this regex (?<=S)(s+).

Examples of input & outputs:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement