☀【组件】字符串 string

时间:2022-01-20 15:16:20
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var string = (function() {
return {
/*
* 功能:去除左右空格
* 来源:JavaScript语言精粹
* http://sofish.de/1600
*/
trim: function(str) {
if (!String.prototype.trim) {
return str.replace(/^\s+|\s+$/g, '')
} else {
return str.trim()
}
}, /*
* 功能:字数限制
* 来源:爆米花
* 依赖:trim
*/
limitText: function(text, length, ellipsis) {
var that = this
text = that.trim(text) var i = 0
var len = text.length
var strCode
var sum = 0 if (length >= len * 2) {
return text
} for (; i < len; i++) {
strCode = text.charCodeAt(i) // 返回指定位置的字符的Unicode编码。这个返回值是0-65535之间的整数 if (strCode <= 126 && strCode >= 32) {
sum++
} else {
sum += 2
} if (length < sum) {
if (ellipsis) {
return text.slice(0, i) + '...'
} else {
return text.slice(0, i) // 0到i,不包括i
}
}
} return text
}, /*
* 功能:字数
* 依赖:trim
*/
getLength: function(str) {
var that = this
str = that.trim(str) return (str.length + str.match(/[^\x00-\x80]/g).length)
}
}
})()
</script>
<script>
console.log(string.trim(' 123 '))
console.log(string.limitText(' 羊羊羊 ', 6, true))
console.log(string.limitText(' 羊羊羊羊羊 ', 6, true))
console.log(string.limitText('羊1羊羊羊', 6))
console.log(string.limitText('羊11羊羊羊', 6))
console.log(string.getLength('羊11羊羊羊'))
// 不要覆盖 String
</script>
</body>
</html>