From 234b2948e7269be8ad38bdd72816c3540291b442 Mon Sep 17 00:00:00 2001 From: James Fredley Date: Wed, 23 Oct 2024 16:18:33 -0400 Subject: [PATCH] add trimToNull method on GrailsStringUtils --- .../grails/util/GrailsStringUtils.groovy | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/grails-core/src/main/groovy/grails/util/GrailsStringUtils.groovy b/grails-core/src/main/groovy/grails/util/GrailsStringUtils.groovy index 85cb80188d7..9233bd55211 100644 --- a/grails-core/src/main/groovy/grails/util/GrailsStringUtils.groovy +++ b/grails-core/src/main/groovy/grails/util/GrailsStringUtils.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2012 the original author or authors. + * Copyright 2012-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -191,4 +191,28 @@ abstract class GrailsStringUtils extends StringUtils{ stripFilenameExtension( getFilename(path) ) } + /** + * Removes all space from both ends of this String returning + * {@code null} if the String is empty ("") after the trim + * or if it is {@code null}. + * + *

The String is trimmed using {@link String#trim()}. + * + *

+     * GrailsStringUtils.trimToNull(null)          = null
+     * GrailsStringUtils.trimToNull("")            = null
+     * GrailsStringUtils.trimToNull("     ")       = null
+     * GrailsStringUtils.trimToNull("xyz")         = "xyz"
+     * GrailsStringUtils.trimToNull("    xyz    ") = "xyz"
+     * 
+ * + * @param str the String to be trimmed, may be null + * @return the trimmed String, + * {@code null} if only containing space, empty or null String input + * @since 7.0.0 + */ + static String trimToNull(String str) { + String trimmed = str?.trim() + return hasLength(trimmed) ? trimmed : null + } }