DEV Community

ouryperd
ouryperd

Posted on

Add left and right trim to String in Groovy

Left trim:

String.metaClass.ltrim = { return delegate.replaceAll(/^* /, '') }

Right trim:

String.metaClass.rtrim = { return delegate.replaceAll(/ *$/, '') }

Usage:

assert ' Groovy'.ltrim() == 'Groovy'
assert 'Groovy '.rtrim() == 'Groovy'
assert ' Groovy'.ltrim() == 'Groovy'
assert 'Groovy '.rtrim() == 'Groovy'

Top comments (0)