Adding a truncate method to a String in Groovy

/ Published in: Groovy
Save to your folder(s)

this truncates a string to a provided length and adds "..." to the end to show that it was truncated.

Copy this code and paste it in your HTML
  1. // this adds a "truncate(#)" method to String and GString
  2. String.metaClass.truncate = {len ->
  3. if (delegate == null) {return ''}
  4. if (delegate.length() > len) {return delegate[0..(len - 4)] + '...'}
  5. return delegate
  6. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.