We can get rid of any trailing spaces using the replace method Given that you also want to cover tabs, newlines, etc, just replace ss with : String string. replace(/ss/g, ) If you really want to cover only spaces (and thus not tabs, newlines, etc), do so: String string. replace(/ /g, ) To find these, I need a RegEx. However, I am falling down on the replace bit. RegEx101 Demo -- correctly identifies the TWO examples where I need to replace the inside space with a marker (such as or something).