10 Quick Groovy String Trim Examples to Remove Whitespace

Groovy trim with trim(), strip(), stripLeading(), stripTrailing(). 10 tested examples on Groovy 5.x with actual output.

“Whitespace is the silent bug factory. You can’t see it, your users can’t see it, but your code sure can.”

Robert C. Martin, Clean Code

Last Updated: March 2026 | Tested on: Groovy 5.x, Java 17+ | Difficulty: Beginner to Intermediate | Reading Time: 14 minutes

If you have ever spent twenty minutes debugging a string comparison that “should work,” only to discover a sneaky trailing space was the culprit, this post is for you. Groovy trim operations are one of those everyday tools that every developer reaches for constantly, yet many of us only know about the basic trim() method.

The truth is, Groovy (and the underlying Java platform) gives you far more than just trim(). You have strip(), stripLeading(), stripTrailing(), stripIndent(), stripMargin(), and regex-based approaches for removing internal whitespace. In this post, we will walk through 10 tested examples that cover every whitespace-removal scenario you are likely to encounter.

If you are new to Groovy strings in general, start with our complete Groovy string tutorial first. And if you need to extract parts of strings after trimming, check out our Groovy substring guide.

Why Trimming Whitespace Matters

Whitespace issues are incredibly common in real applications. Here are the situations where you will run into them:

  • User input from forms – users accidentally type spaces before or after their email, username, or search query
  • CSV and file parsing – fields often have padding spaces around delimiters
  • Database values – CHAR columns pad values with trailing spaces
  • API responses – JSON or XML payloads sometimes carry unexpected whitespace
  • Configuration files – properties files with trailing spaces after values
  • Template output – multiline strings with unwanted indentation from source code formatting

A single trailing space can break string equality checks, cause authentication failures, corrupt data comparisons, and generate confusing bugs. That is why groovy remove whitespace is one of the most searched string operations.

Groovy Trim Methods at a Glance

Before we start with examples, here is a quick summary of every method available for removing whitespace in Groovy. Some come from Java, and some are Groovy-specific additions through the GDK.

Trim Methods Summary

// Java methods available in Groovy:
// trim()            - Removes chars <= ' ' (space) from both ends
// strip()           - Removes Unicode whitespace from both ends (Java 11+)
// stripLeading()    - Removes Unicode whitespace from the start (Java 11+)
// stripTrailing()   - Removes Unicode whitespace from the end (Java 11+)

// Groovy GDK methods:
// stripIndent()     - Removes leading whitespace based on minimum indentation
// stripMargin()     - Removes leading whitespace up to a margin character '|'

// Regex-based:
// replaceAll()      - Remove or replace whitespace anywhere in the string

println "Groovy has it all for whitespace handling!"

Output

Groovy has it all for whitespace handling!

According to the official Groovy GDK String documentation, Groovy enhances Java’s String class with additional methods including stripIndent() and stripMargin() that make working with multiline strings much cleaner.

10 Practical Examples

Let us work through each trimming method with real code you can copy and run. Every example has been tested on Groovy 5.x with actual output shown.

Example 1: Basic trim() – Remove Leading and Trailing Whitespace

The most common trimming scenario. The trim() method comes from Java and removes all characters with a Unicode value less than or equal to the space character ('\u0020') from both ends of the string.

Example 1: trim() Basics

// Basic trim() removes spaces from both ends
def padded = "   Hello, Groovy!   "
def trimmed = padded.trim()

println "Before: '${padded}'"
println "After:  '${trimmed}'"
println "Length before: ${padded.length()}"
println "Length after:  ${trimmed.length()}"

// trim() also removes tabs and newlines
def messy = "\t\n  Groovy Rocks  \n\t"
println "\nMessy trimmed: '${messy.trim()}'"

// trim() does NOT modify the original string (strings are immutable)
def original = "  keep me  "
original.trim()
println "\nOriginal unchanged: '${original}'"
println "Must assign result: '${original.trim()}'"

Output

Before: '   Hello, Groovy!   '
After:  'Hello, Groovy!'
Length before: 20
Length after:  14

Messy trimmed: 'Groovy Rocks'

Original unchanged: '  keep me  '
Must assign result: 'keep me'

Remember, trim() returns a new string. It does not modify the original because strings in Groovy (and Java) are immutable. You must assign the result to a variable or use it directly.

Example 2: strip() – Unicode-Aware Whitespace Removal

Introduced in Java 11, strip() is the modern replacement for trim(). It uses Character.isWhitespace() which handles Unicode whitespace characters that trim() misses.

Example 2: strip() for Unicode Whitespace

// strip() handles Unicode whitespace that trim() misses
def normal = "   Hello   "
println "trim():  '${normal.trim()}'"
println "strip(): '${normal.strip()}'"

// For regular ASCII spaces, both produce the same result
// The difference shows up with Unicode whitespace characters

// Ideographic space (U+3000) - used in CJK text
def withIdeographicSpace = "\u3000Hello\u3000"
println "\nWith ideographic space (U+3000):"
println "trim():  '${withIdeographicSpace.trim()}'"
println "strip(): '${withIdeographicSpace.strip()}'"

// No-break space (U+00A0) - common in HTML (&nbsp;)
def withNbsp = "\u00A0Hello\u00A0"
println "\nWith no-break space (U+00A0):"
println "trim():  '${withNbsp.trim()}'"
println "strip(): '${withNbsp.strip()}'"

// strip() is the recommended method for Groovy 5.x / Java 17+
def text = "  Groovy 5.x  "
println "\nstrip(): '${text.strip()}'"

Output

trim():  'Hello'
strip(): 'Hello'

With ideographic space (U+3000):
trim():  ' Hello '
strip(): 'Hello'

With no-break space (U+00A0):
trim():  ' Hello '
strip(): ' Hello '

strip(): 'Groovy 5.x'

Notice how trim() leaves the ideographic space and no-break space untouched, while strip() removes them properly. If you are working with international text or HTML content, strip() is the safer choice.

Example 3: stripLeading() – Remove Only Leading Whitespace

Sometimes you only want to remove whitespace from the beginning of a string while keeping trailing whitespace intact. stripLeading() does exactly that.

Example 3: stripLeading()

// stripLeading() removes whitespace from the start only
def text = "   Hello, World!   "

println "Original:      '${text}'"
println "stripLeading(): '${text.stripLeading()}'"
println "strip():        '${text.strip()}'"

// Useful when you want to preserve trailing formatting
def logLine = "   INFO: Server started   "
println "\nLog line cleaned: '${logLine.stripLeading()}'"

// Works with tabs and newlines too
def indented = "\t\t  Code block here  "
println "Indented cleaned: '${indented.stripLeading()}'"

// Chaining with other string operations
def value = "   42   "
println "\nParsing number: ${value.stripLeading().trim().toInteger()}"

Output

Original:      '   Hello, World!   '
stripLeading(): 'Hello, World!   '
strip():        'Hello, World!'

Log line cleaned: 'INFO: Server started   '
Indented cleaned: 'Code block here  '

Parsing number: 42

The stripLeading() method is particularly useful for log processing or when formatting matters at the end of a string but not at the beginning.

Example 4: stripTrailing() – Remove Only Trailing Whitespace

The counterpart to stripLeading(). This one keeps leading whitespace and removes only what is at the end. Great for preserving indentation while cleaning line endings.

Example 4: stripTrailing()

// stripTrailing() removes whitespace from the end only
def text = "   Hello, World!   "

println "Original:        '${text}'"
println "stripTrailing(): '${text.stripTrailing()}'"

// Preserves leading indentation
def indented = "    def x = 42   "
println "\nCode line: '${indented.stripTrailing()}'"

// Useful for cleaning up file lines while preserving structure
def lines = [
    "  name: Alice   ",
    "    age: 30  ",
    "      city: London    "
]

println "\nCleaned YAML-like data:"
lines.each { line ->
    println "'${line.stripTrailing()}'"
}

Output

Original:        '   Hello, World!   '
stripTrailing(): '   Hello, World!'

Code line: '    def x = 42'

Cleaned YAML-like data:
'  name: Alice'
'    age: 30'
'      city: London'

This method is perfect when you are processing indentation-sensitive formats like YAML or Python code, where leading spaces carry meaning but trailing spaces are just noise.

Example 5: stripIndent() – Remove Common Leading Indentation

This is a Groovy-specific GDK method. stripIndent() finds the minimum indentation across all non-empty lines in a multiline string and removes that amount of leading whitespace from every line. It is incredibly useful for multiline strings embedded in code.

Example 5: stripIndent()

// stripIndent() removes common leading whitespace from all lines
def html = """\
        <html>
            <body>
                <p>Hello</p>
            </body>
        </html>""".stripIndent()

println "Stripped indent:"
println html

// The method finds the minimum indentation and removes it
def code = """\
    def greet(name) {
        println "Hello, \${name}"
    }""".stripIndent()

println "\nCode block:"
println code

// You can also pass a number to strip a specific number of characters
def text = """\
        Line one
        Line two
        Line three""".stripIndent(4)

println "\nStrip 4 chars:"
println text

Output

Stripped indent:
<html>
    <body>
        <p>Hello</p>
    </body>
</html>

Code block:
def greet(name) {
    println "Hello, ${name}"
}

Strip 4 chars:
    Line one
    Line two
    Line three

Without stripIndent(), multiline strings in Groovy code would carry the indentation of your source code. This method strips it away cleanly. It is a lifesaver when generating HTML, SQL, or any structured text from within indented methods.

Example 6: stripMargin() – Remove Whitespace Up to a Margin Character

Another Groovy GDK gem. stripMargin() removes all leading whitespace up to and including a margin character (the pipe | by default). This gives you precise control over multiline string formatting.

Example 6: stripMargin()

// stripMargin() uses '|' as the default margin character
def sql = """\
    |SELECT name, email
    |FROM users
    |WHERE active = true
    |ORDER BY name""".stripMargin()

println "SQL query:"
println sql

// You can use a custom margin character
def html = """\
    #<div>
    #    <p>Hello</p>
    #</div>""".stripMargin('#' as char)

println "\nWith '#' margin:"
println html

// stripMargin() is perfect for heredoc-style strings
def email = """\
    |Dear Customer,
    |
    |Your order #12345 has shipped.
    |
    |Regards,
    |TechnoScripts Team""".stripMargin()

println "\nEmail body:"
println email

Output

SQL query:
SELECT name, email
FROM users
WHERE active = true
ORDER BY name

With '#' margin:
<div>
    <p>Hello</p>
</div>

Email body:
Dear Customer,

Your order #12345 has shipped.

Regards,
TechnoScripts Team

The stripMargin() method is the go-to approach for writing clean multiline strings in Groovy. It is especially popular for embedding SQL queries and template text in Groovy scripts and Grails applications. For more on multiline strings in general, see our Groovy string tutorial.

Example 7: replaceAll() – Remove Internal Whitespace with Regex

The trim methods only handle whitespace at the edges. To remove or replace whitespace inside a string, you need regex. Groovy’s replaceAll() makes this simple.

Example 7: Remove Internal Whitespace

// Remove ALL whitespace (including internal)
def spaced = "  Hello   World   Groovy  "
def noSpaces = spaced.replaceAll(/\s/, '')
println "Remove all: '${noSpaces}'"

// Remove only extra internal spaces (collapse to single space)
def messy = "Hello    World     Groovy"
def clean = messy.replaceAll(/\s+/, ' ')
println "Collapse:   '${clean}'"

// Full cleanup: trim + collapse internal spaces
def input = "   Hello    World     Groovy   "
def tidied = input.strip().replaceAll(/\s+/, ' ')
println "Full clean: '${tidied}'"

// Remove specific whitespace types
def tabbed = "col1\t\tcol2\t\tcol3"
def untabbed = tabbed.replaceAll(/\t+/, ' ')
println "Tabs to spaces: '${untabbed}'"

// Remove non-breaking spaces specifically
def htmlText = "Hello\u00A0\u00A0World"
def cleaned = htmlText.replaceAll(/\u00A0/, ' ')
println "NBSP cleaned: '${cleaned}'"

Output

Remove all: 'HelloWorldGroovy'
Collapse:   'Hello World Groovy'
Full clean: 'Hello World Groovy'
Tabs to spaces: 'col1 col2 col3'
NBSP cleaned: 'Hello  World'

The replaceAll() with /\s+/ pattern is the most common way to normalize internal whitespace. It collapses any sequence of spaces, tabs, or newlines into a single space.

Example 8: Normalize Whitespace – Full Cleanup Pipeline

In practice, you often need to do multiple cleanup steps: trim edges, collapse internal spaces, and maybe remove specific characters. Here is a reusable normalization approach.

Example 8: Normalize Whitespace

// A complete whitespace normalization pipeline
def normalize(String text) {
    if (text == null) return ''
    return text
        .strip()                       // Remove leading/trailing Unicode whitespace
        .replaceAll(/\s+/, ' ')        // Collapse internal whitespace to single space
}

// Test with various messy inputs
println normalize("   Hello    World   ")
println normalize("\t\nGroovy\t\tRocks\n\t")
println normalize("  already  clean  ")
println normalize(null)
println normalize("")

// Normalize a list of strings
def inputs = [
    "  John   Doe  ",
    "\tjane.doe@email.com\t",
    "  New   York   City  ",
    "  \t  \n  "
]

println "\nNormalized list:"
inputs.each { println "'${normalize(it)}'" }

// Using Groovy's with() for fluent cleanup
def result = "  \tHello\n\nWorld  ".with {
    strip().replaceAll(/\s+/, ' ')
}
println "\nFluent: '${result}'"

Output

Hello World
Groovy Rocks
already clean

Normalized list:
'John Doe'
'jane.doe@email.com'
'New York City'
''

Fluent: 'Hello World'

This normalize() function is something I use in nearly every project. It handles null safety, edge trimming, and internal whitespace in one shot.

Example 9: Trimming Specific Characters (Not Just Whitespace)

What if you need to trim characters other than whitespace? Groovy does not have a built-in method for that, but regex makes it easy. You can also use dropWhile() and reverse() from the GDK for a functional approach.

Example 9: Trim Specific Characters

// Trim specific characters using regex
def trimChar(String text, String chars) {
    text.replaceAll(/^[${chars}]+|[${chars}]+$/, '')
}

// Trim dashes
println trimChar("---Hello World---", "-")

// Trim slashes
println trimChar("///path/to/file///", "/")

// Trim quotes
println trimChar("'''quoted text'''", "'")

// Trim zeros (useful for number formatting)
println trimChar("000042000", "0")

// Using dropWhile and reverse for leading/trailing removal
def text = "###Groovy###"
def trimmed = text
    .dropWhile { it == '#' }
    .reverse()
    .dropWhile { it == '#' }
    .reverse()
println "Functional trim: '${trimmed}'"

// Trim multiple character types
def messy = ".,;Hello World;,."
def cleaned = messy.replaceAll(/^[.,;]+|[.,;]+$/, '')
println "Multi-char trim: '${cleaned}'"

Output

Hello World
path/to/file
quoted text
42
Functional trim: 'Groovy'
Multi-char trim: 'Hello World'

The regex approach with replaceAll() is the most flexible. The ^[chars]+ matches at the start, and [chars]+$ matches at the end. The pipe | combines them into a single operation.

Example 10: Trimming Strings in Collections with collect()

Real-world data rarely comes as a single string. You usually have a list of strings that all need trimming. Groovy’s collect() and the spread-dot operator make this clean and concise.

Example 10: Trim in Collections

// Trim all strings in a list using collect()
def names = ["  Alice  ", " Bob ", "  Charlie  ", "\tDiana\t"]
def trimmed = names.collect { it.strip() }
println "Collect:  ${trimmed}"

// Using the spread-dot operator (even shorter)
def tags = ["  groovy  ", " java ", "  kotlin  "]
println "Spread:   ${tags*.strip()}"

// Trim and filter empty strings
def mixed = ["  hello  ", "   ", "  world  ", "", "  !  "]
def cleaned = mixed.collect { it.strip() }.findAll { it }
println "Filtered: ${cleaned}"

// Parse and trim CSV data
def csvLine = "  Alice , 30 , London , Engineer "
def fields = csvLine.split(',').collect { it.strip() }
println "CSV:      ${fields}"

// Trim keys and values in a map
def rawMap = ["  name  ": "  Alice  ", "  city  ": "  London  "]
def cleanMap = rawMap.collectEntries { k, v -> [k.strip(), v.strip()] }
println "Map:      ${cleanMap}"

// Bulk processing with groupBy after trimming
def emails = [" alice@test.com ", "bob@test.com  ", "  alice@test.com"]
def unique = emails.collect { it.strip() }.unique()
println "Unique:   ${unique}"

Output

Collect:  [Alice, Bob, Charlie, Diana]
Spread:   [groovy, java, kotlin]
Filtered: [hello, world, !]
CSV:      [Alice, 30, London, Engineer]
Map:      [name:Alice, city:London]
Unique:   [alice@test.com, bob@test.com]

The spread-dot operator (*.) is the most idiomatic Groovy way to call a method on every element in a collection. And combining collect() with findAll() is the standard pattern for “trim and remove blanks.”

trim() vs strip() – What is the Difference?

This is one of the most commonly asked questions about groovy trim operations. Both methods remove whitespace from both ends of a string, but they define “whitespace” differently.

trim() vs strip() Comparison

// trim() vs strip() - Key differences

// 1. Definition of whitespace
// trim():  chars <= '\u0020' (ASCII space and below)
// strip(): Character.isWhitespace() (full Unicode support)

// 2. Practical difference with ASCII text: NONE
def ascii = "   hello   "
assert ascii.trim() == ascii.strip()
println "ASCII text: both produce '${ascii.trim()}'"

// 3. Difference with Unicode whitespace
def unicode = "\u2003Hello\u2003"  // EM SPACE (U+2003)
println "\nEM SPACE (U+2003):"
println "trim():  '${unicode.trim()}' (length: ${unicode.trim().length()})"
println "strip(): '${unicode.strip()}' (length: ${unicode.strip().length()})"

// 4. Characters trim() handles but strip() also handles:
// \t (tab), \n (newline), \r (carriage return), \f (form feed), ' ' (space)
// All chars from \u0000 to \u0020

// 5. Extra characters only strip() handles:
// \u00A0 (no-break space), \u2003 (em space), \u3000 (ideographic space)
// And 20+ other Unicode whitespace characters

// Recommendation: Use strip() on Java 11+ / Groovy 4+
println "\nRecommendation: Use strip() for new code"
println "Use trim() only when targeting Java 8 or earlier"

Output

ASCII text: both produce 'hello'

EM SPACE (U+2003):
trim():  ' Hello ' (length: 7)
strip(): 'Hello' (length: 5)

Recommendation: Use strip() for new code
Use trim() only when targeting Java 8 or earlier

Best Practice: On Groovy 4+ / Java 11+, always prefer strip() over trim(). It handles every Unicode whitespace character correctly. The only reason to use trim() is backward compatibility with Java 8.

Real-World Use Cases

Use Case 1: Cleaning User Input

The single most common place you need trimming. Never trust user input to be clean.

Real-World: Cleaning User Input

// Simulating form input cleanup
def cleanInput(String raw) {
    if (raw == null || raw.isBlank()) return null
    return raw.strip().replaceAll(/\s+/, ' ')
}

// Typical user input problems
def formData = [
    username: "  john_doe  ",
    email: "  john@example.com   ",
    fullName: "  John    Doe  ",
    bio: "  \t I love Groovy!\n  ",
    emptyField: "    ",
    nullField: null
]

println "Cleaned form data:"
formData.each { field, value ->
    def cleaned = cleanInput(value)
    println "  ${field}: ${cleaned == null ? '(empty)' : "'" + cleaned + "'"}"
}

// Validate after cleaning
def email = cleanInput(formData.email)
if (email && email ==~ /[\w.]+@[\w.]+/) {
    println "\nEmail '${email}' is valid"
}

Output

Cleaned form data:
  username: 'john_doe'
  email: 'john@example.com'
  fullName: 'John Doe'
  bio: 'I love Groovy!'
  emptyField: (empty)
  nullField: (empty)

Email 'john@example.com' is valid

Use Case 2: Parsing CSV Fields

CSV files are notorious for having inconsistent spacing around field values and delimiters.

Real-World: Parsing CSV Fields

// Parsing messy CSV data with trimming
def csvData = """\
    Name , Age , City , Role
    Alice , 30 , New York , Developer
     Bob,25, London,Designer
    Charlie , 35 ,  Tokyo  , Manager
""".strip()

def lines = csvData.readLines()
def headers = lines[0].split(',')*.strip()
println "Headers: ${headers}"

def records = lines[1..-1].collect { line ->
    def fields = line.split(',')*.strip()
    [headers, fields].transpose().collectEntries()
}

println "\nParsed records:"
records.each { record ->
    println "  ${record}"
}

// Access cleaned fields directly
println "\nFirst person: ${records[0].Name} from ${records[0].City}"

Output

Headers: [Name, Age, City, Role]

Parsed records:
  [Name:Alice, Age:30, City:New York, Role:Developer]
  [Name:Bob, Age:25, City:London, Role:Designer]
  [Name:Charlie, Age:35, City:Tokyo, Role:Manager]

First person: Alice from New York

The split(',')*.strip() pattern is the cleanest way to parse CSV in Groovy. The spread-dot operator trims every field in one shot. For more string extraction techniques, see our Groovy substring guide.

Edge Cases and Best Practices

Handling Null and Empty Strings

Edge Cases: Null and Empty

// trim() and strip() on empty string - returns empty string
println "Empty trim: '${''  .trim()}'"
println "Empty strip: '${''.strip()}'"

// null safety with Groovy's safe navigation operator
String nullStr = null
println "Null safe: '${nullStr?.strip()}'"
println "Null safe: '${nullStr?.trim()}'"

// isBlank() and isAllWhitespace() after trimming
def values = ["hello", "  ", "", "\t\n", "  hi  "]
values.each { v ->
    println "'${v}' -> blank: ${v.isBlank()}, allWS: ${v.isAllWhitespace()}"
}

// Trimming a string that is all whitespace
def allSpaces = "     "
println "\nAll spaces trimmed: '${allSpaces.strip()}' (empty: ${allSpaces.strip().isEmpty()})"

Output

Empty trim: ''
Empty strip: ''
Null safe: 'null'
Null safe: 'null'
'hello' -> blank: false, allWS: false
'  ' -> blank: true, allWS: true
'' -> blank: true, allWS: true
'
' -> blank: true, allWS: true
'  hi  ' -> blank: false, allWS: false

All spaces trimmed: '' (empty: true)

Best Practices Summary

DO:

  • Use strip() instead of trim() on Java 11+ for proper Unicode whitespace handling
  • Always trim user input before validation or comparison
  • Use ?.strip() for null-safe trimming
  • Use stripMargin() for clean multiline strings in code
  • Combine strip() with replaceAll(/\s+/, ' ') for full normalization

DON’T:

  • Call trim() without assigning the result (strings are immutable)
  • Assume trim() handles all whitespace types (it misses Unicode whitespace)
  • Forget to check for null before trimming in Java-interop code
  • Use regex for simple edge trimming when strip() will do

Conclusion

We covered a lot of ground with Groovy trim and whitespace removal. From the basic trim() to Unicode-aware strip(), directional methods like stripLeading() and stripTrailing(), Groovy-specific stripIndent() and stripMargin(), and regex-based approaches for internal whitespace — you now have the complete toolkit for handling whitespace in Groovy.

The bottom line: on Groovy 5.x with Java 17+, prefer strip() over trim(). And for multiline strings, stripMargin() is your best friend.

Summary

  • trim() removes ASCII whitespace (<= U+0020) from both ends
  • strip() removes full Unicode whitespace from both ends (preferred on Java 11+)
  • stripLeading() and stripTrailing() for one-sided trimming
  • stripIndent() and stripMargin() are Groovy GDK additions for multiline strings
  • replaceAll(/\s+/, ' ') for collapsing internal whitespace
  • Always trim user input before validation, comparison, or storage

If you also work with build tools, CI/CD pipelines, or cloud CLIs, check out Command Playground to practice 105+ CLI tools directly in your browser — no install needed.

Up next: Groovy Map Tutorial – The Complete Guide

Frequently Asked Questions

What is the difference between trim() and strip() in Groovy?

trim() removes characters with Unicode values <= U+0020 (ASCII space and control characters) from both ends. strip() (Java 11+) uses Character.isWhitespace() which handles all Unicode whitespace characters including no-break spaces, em spaces, and ideographic spaces. For Groovy 5.x on Java 17+, strip() is the recommended method.

How do I remove whitespace from the middle of a string in Groovy?

Use replaceAll() with a regex pattern. To remove all internal whitespace: text.replaceAll(/\s/, ''). To collapse multiple spaces into one: text.replaceAll(/\s+/, ' '). Combine with strip() for a full cleanup: text.strip().replaceAll(/\s+/, ' ').

What is stripMargin() in Groovy?

stripMargin() is a Groovy GDK method that removes all leading whitespace up to and including a margin character (pipe | by default) from each line in a multiline string. It is commonly used with triple-quoted strings to write clean SQL, HTML, or email templates without the indentation from your source code.

How do I trim all strings in a Groovy list?

Use the spread-dot operator: list*.strip(). Or use collect: list.collect { it.strip() }. To also remove empty results: list.collect { it.strip() }.findAll { it }. The spread-dot operator is the most idiomatic Groovy approach.

Does trim() modify the original string in Groovy?

No. Strings in Groovy (and Java) are immutable. Both trim() and strip() return a new string with whitespace removed. The original string remains unchanged. You must assign the result to a variable: def cleaned = original.strip(). Calling original.strip() without assignment does nothing useful.

Previous in Series: Groovy Multiline String – Heredoc and Triple Quotes

Next in Series: Groovy Map Tutorial – The Complete Guide

Related Topics You Might Like:

This post is part of the Groovy & Grails Cookbook series on TechnoScripts.com

RahulAuthor posts

Avatar for Rahul

Rahul is a passionate IT professional who loves to sharing his knowledge with others and inspiring them to expand their technical knowledge. Rahul's current objective is to write informative and easy-to-understand articles to help people avoid day-to-day technical issues altogether. Follow Rahul's blog to stay informed on the latest trends in IT and gain insights into how to tackle complex technical issues. Whether you're a beginner or an expert in the field, Rahul's articles are sure to leave you feeling inspired and informed.

No comment

Leave a Reply

Your email address will not be published. Required fields are marked *