Golang : Underscore string example
Problem:
Your program needs to process data with whitespaces and quotes. You need a quick way to remove underscore characters from a string's start and end positions. You also want to replace white spaces and quotes to underscore "_
".
How to do that?
Solution:
Here you go!
package main
import (
"fmt"
"regexp"
"strings"
)
func UnderScoreString(str string) string {
// convert every letter to lower case
newStr := strings.ToLower(str)
// convert all spaces/tab to underscore
regExp := regexp.MustCompile("[[:space:][:blank:]]")
newStrByte := regExp.ReplaceAll([]byte(newStr), []byte("_"))
regExp = regexp.MustCompile("`[^a-z0-9]`i")
newStrByte = regExp.ReplaceAll(newStrByte, []byte("_"))
regExp = regexp.MustCompile("[!/']")
newStrByte = regExp.ReplaceAll(newStrByte, []byte("_"))
// and remove underscore from beginning and ending
newStr = strings.TrimPrefix(string(newStrByte), "_")
newStr = strings.TrimSuffix(newStr, "_")
return newStr
}
func main() {
test := "That is Peter's House"
fmt.Println(UnderScoreString(test))
test1 := "Peter's House!"
fmt.Println(UnderScoreString(test1))
test2 := "_88 is Peter's House number_"
fmt.Println(UnderScoreString(test2))
}
Output :
that_is_peter_s_house
peter_s_house
88_is_peter_s_house_number
Reference:
https://www.socketloop.com/tutorials/golang-format-strings-to-seo-friendly-url-example
See also : Golang : Format strings to SEO friendly URL example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.2k Golang : Convert Unix timestamp to UTC timestamp
+7.9k Golang : Routes multiplexer routing example with regular expression control
+10.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+9.1k Golang : How to protect your source code from client, hosting company or hacker?
+16.8k Golang : XML to JSON example
+8.2k Golang : How to check variable or object type during runtime?
+7.2k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+11.1k Golang : Delay or limit HTTP requests example
+33.7k Golang : Call a function after some delay(time.Sleep and Tick)
+51.6k Golang : How to get time in milliseconds?
+5.8k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+9k Golang : How to control fmt or log print format?