Go strings.ReplaceAll
Replace every literal hyphen in a warehouse code with a slash.
A simple example
strings.ReplaceAll
- Start with "a-b"
- Do this Replace the hyphen with a space
- Result "a b"
package main
import (
"fmt"
"strings"
)
func main() {
value := "a-b"
fmt.Println(strings.ReplaceAll(value, "-", " "))
}
a b
Syntax
strings.ReplaceAll(label, "-", "/")
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goPrint a shelf code with readable separators
A printed code uses separators or spacing that are awkward for a reader. Convert the display copy to the desired format and preserve the original value needed by the source system.
package main
import (
"fmt"
"strings"
)
func main() {
label := "A-12-B"
fmt.Println(strings.ReplaceAll(label, "-", "/"))
}
A/12/B
Both separators change and the order of the individual code fields stays the same.
Display a course slug
A course directory stores a short slug for linking between pages. Derive its display spelling when showing the course so readers see the intended label while the stored slug remains usable.
package main
import (
"fmt"
"strings"
)
func main() {
value := "data-science"
fmt.Println(strings.ReplaceAll(value, "-", " "))
}
data science
The two words are separated for display.
Display a route slug
A directory stores a public name as a short slug. Turn the stored spelling into the display form required by the interface while keeping the identifier used for lookup available separately.
package main
import (
"fmt"
"strings"
)
func main() {
value := "north-gate-two"
fmt.Println(strings.ReplaceAll(value, "-", " "))
}
north gate two
Each literal hyphen is replaced.
What to watch for
A literal replacement and a regular-expression replacement treat punctuation differently.