Add left and right trim to String in Groovy

ou_ryperd

ouryperd

Posted on April 11, 2022

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'

💖 💪 🙅 🚩
ou_ryperd
ouryperd

Posted on April 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related