How do I trim whitespace from a string in EK9?

← Common String Operations · Ref: Q173

EK9 strings have .trim() for whitespace removal and .trim(char) for removing a specific character.

TRIM WHITESPACE

Remove leading and trailing whitespace:

  cleaned <- myString.trim()

Returns a new string with spaces, tabs, and newlines removed from both ends.

TRIM SPECIFIC CHARACTER

Remove a specific character from both ends:

  unquoted <- myString.trim('"')

Useful for removing surrounding quotes or delimiters.

COMBINE WITH PADDING

Trim is the complement of padding:

  padded <- myString.rightPadded(30)
  trimmed <- padded.trim()

See Q37 for comprehensive string operations. See Q176 for string padding. See Q172 for string case. See Q174 for string concat. See Q175 for string transform.

Example

defines module qa.stringops.trim

  defines program
    StringTrimDemo()
      stdout <- Stdout()

      // === TRIM WHITESPACE ===

      padded <- "  Hello World  "
      trimmed <- padded.trim()
      stdout.println(`Before: [${padded}]`)
      stdout.println(`After trim: [${trimmed}]`)

      // === TRIM SPECIFIC CHARACTER ===

      quoted <- "\"Hello World\""
      unquoted <- quoted.trim('"')
      stdout.println(`Quoted: ${quoted}`)
      stdout.println(`Unquoted: ${unquoted}`)

      dashed <- "---Title---"
      undashed <- dashed.trim('-')
      stdout.println(`Dashed: ${dashed}`)
      stdout.println(`Undashed: ${undashed}`)

      // === COMPLEMENT OF PADDING ===

      original <- "Test"
      rightPad <- original.rightPadded(20)
      stdout.println(`Right padded: [${rightPad}]`)

      backToOriginal <- rightPad.trim()
      stdout.println(`Trimmed back: [${backToOriginal}]`)

Common mistakes

E50060 — String has no strip() method. The correct method name in EK9 is trim(). See ek9 -h E50060 for details.

Incorrect:

trimmed <- padded.strip()

Correct:

trimmed <- padded.trim()

E50060 — String has no trimLeft() method. EK9 provides trim() for both ends and trim(char) for a specific character. Use 'ek9 -h String' to see the full API. See ek9 -h E50060 for details.

Incorrect:

trimmed <- padded.trimLeft()

Correct:

trimmed <- padded.trim()
Other ways to ask this
  • How do I remove leading and trailing spaces from a string in EK9?
  • What is the EK9 equivalent of string.trim()?
  • How do I strip whitespace from a string in EK9?

Coming from another language?

Java: str.trim(), str.strip() (Java 11+). Python: str.strip(), str.strip(chars). Rust: str.trim(), str.trim_matches(char). Go: strings.TrimSpace(), strings.Trim(). JavaScript: str.trim(). Kotlin: str.trim(), str.trim(char). EK9: str.trim(), str.trim(char).

Keywords: trailing, clean, whitespace, strip, text, leading, spaces, trim, string