Last active
September 27, 2015 08:17
-
-
Save bachvtuan/80f4815f3812684d955f to your computer and use it in GitHub Desktop.
Generate unicode slug in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"unicode" | |
"code.google.com/p/go.text/transform" | |
"code.google.com/p/go.text/unicode/norm" | |
"regexp" | |
"strings" | |
) | |
func isMn(r rune) bool { | |
return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks | |
} | |
var re = regexp.MustCompile("[^a-z0-9]+") | |
var t = transform.Chain( norm.NFD, transform.RemoveFunc(isMn), norm.NFC ) | |
func GenerateSlug( s string ) string { | |
s = FixUnicode( s ) | |
result, _, _ := transform.String(t, s) | |
return strings.Trim(re.ReplaceAllString(strings.ToLower( result ), "-"), "-") | |
} | |
/** | |
* Short the string by word count first then do slug | |
*/ | |
func GenerateShortSlug( s string, word_count int ) string { | |
arr_words := strings.Split( s , " ") | |
if len(arr_words) < word_count{ | |
return GenerateSlug( s ) | |
} | |
arr_words = arr_words[:word_count] | |
return GenerateSlug( strings.Join( arr_words, " " ) ) | |
} | |
/** | |
* Logic some cases that unicode lib can not resolve | |
*/ | |
func FixUnicode( s string ) string { | |
r := strings.NewReplacer("đ", "d") | |
return r.Replace( s ) | |
} | |
func main() { | |
fmt.Println( GenerateSlug("Hệ thống trợ lực điện trên vô lăng tích hợp cảm biến điều chỉnh độ chắc chắn của tay lái.") ) | |
fmt.Println( GenerateSlug("žůžo") ) | |
fmt.Println( GenerateShortSlug("Thêm một chiếc F-150 nữa sẽ được thông quan vào tuần sau, và là chiếc F-150 Plantinum 2015 thứ 3 tại Việt Nam. ", 10) ) | |
fmt.Println( GenerateShortSlug("Xế độc Ford F-150 Platinum 2015 đầu tiên ở Sài Gòn", 10) ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment