Library contents

Go strings.TrimSpace

Remove surrounding whitespace before looking up a booking.

A simple example

strings.TrimSpace

  1. Start with " A "
  2. Do this Remove surrounding spaces
  3. Result "A"
The middle letter stays in place while both ends lose their spaces.
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "  A  "
    fmt.Println(strings.TrimSpace(value))
}
Output
A

Syntax

Go syntax
strings.TrimSpace(label)
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Clean up a copied booking code

A booking number copied from a confirmation email includes whitespace around it. Prepare the value for an exact lookup without deleting characters that belong inside the number.

From the programlabel := " AB-17 "
ResultAB-17
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    label := "  AB-17  "
    fmt.Println(strings.TrimSpace(label))
}
Output
AB-17

Padding disappears while the hyphen in the middle is kept.

Advertisements

Clean a pasted receipt code

A cashier pastes a receipt identifier that includes stray whitespace from a spreadsheet. Clean the outer characters before using the code to retrieve the matching transaction.

From the programvalue := " AB-17 "
ResultAB-17
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "  AB-17  "
    fmt.Println(strings.TrimSpace(value))
}
Output
AB-17

Both margins disappear from the copied code.

Keep the space inside a course title

A user pastes a name or code from another application. Remove the unwanted outer padding while preserving the spaces and letters that belong to the actual value.

From the programvalue := "\tData Science "
ResultData Science
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "\tData Science "
    fmt.Println(strings.TrimSpace(value))
}
Output
Data Science

The space between the two words remains.

What to watch for

The set of removable whitespace characters differs between APIs. This example uses ordinary spaces.

Documentation for strings.TrimSpace