Skip to content

Function trim()

📝 Description

The trim function removes specified characters from the start and end of a string. It stops as soon as it hits a character that is not in your "cutset".

Use Case: Cleaning up quotes from a string, removing accidental slashes from the end of a URL, or stripping brackets.


💻 Syntax

trim(string, cutset)
  • string: The text you want to clean.

  • cutset: A string containing all the characters you want to remove (the order doesn't matter).


💡 Examples

1. Stripping Quotes:

Common when parsing raw text or CSV data.

# Result: "important_value"
output "clean_data" {
  value = trim("\"important_value\"", "\"")
}

2. Cleaning a URL Path:

Removing trailing or leading slashes to ensure a valid path.

# Result: "api/v1/users"
output "clean_path" {
  value = trim("///api/v1/users//", "/")
}

3. Removing Multiple Symbols:

The cutset can include many characters at once.

# Result: "hello"
output "clean_symbols" {
  value = trim("?!hello!??!", "?!")
}

⚠️ The "Trim Family" (Quick Reference)

Function What it does
trimspace() Removes all whitespace (spaces, tabs, newlines) from both ends.
trimprefix() Removes a specific prefix from the start (e.g., trimprefix("www.google.com", "www.")).
trimsuffix() Removes a specific suffix from the end (e.g., trimsuffix("file.txt", ".txt")).

  • [[chomp]] — Specifically for newlines at the end.

  • [[replace]] — Better if you need to remove characters from the middle of a string.

  • Official HashiCorp Docs