1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package util
- import (
- "strings"
- strip "github.com/grokify/html-strip-tags-go"
- )
- // TruncateRune 截断字符串长度为length的子串,不限制汉字或英文
- // 输入:length,截止的字数,包括汉字和英文的个数
- // 输出:没有空格[ ]、换行[\n]、制表符[\t]的字符串
- func TruncateRune(s string, length int) string {
- // 删除空格与换行字符
- s = strings.Replace(s, " ", "", -1)
- s = strings.Replace(s, "\n", "", -1)
- s = strings.Replace(s, "\t", "", -1)
- rs := []rune(s)
- len := len(rs)
- if length > len {
- length = len
- }
- return string(rs[0:length])
- }
- // TruncateRuneNoHtmlTags 截断字符串长度为length的子串,不限制汉字或英文
- // 输入:length,截止的字数,包括汉字和英文的个数
- // 输出:没有空格[ ]、换行[\n]、制表符[\t]和html标签的字符串
- func TruncateRuneNoHtmlTags(s string, length int) string {
- // 删除空格与换行字符
- s = strings.Replace(s, " ", "", -1)
- s = strings.Replace(s, "\n", "", -1)
- s = strings.Replace(s, "\t", "", -1)
- s = strip.StripTags(s)
- rs := []rune(s)
- len := len(rs)
- if length > len {
- length = len
- }
- return string(rs[0:length])
- }
|