Refactored `trim` function to get rid of some duplication