Skip to content
This repository was archived by the owner on Nov 8, 2022. It is now read-only.

Commit fa39bbb

Browse files
committed
refactor(utils): cutFrom support complex chinese char
1 parent 4a83cfa commit fa39bbb

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

utils/functions.js

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import PubSub from 'pubsub-js'
44
import { TAG_COLOR_ORDER } from '@config'
55
import { EVENT } from '@constant'
66

7-
import { nilOrEmpty } from './validator'
8-
97
/* eslint-disable */
108
// TODO: document ?
119
export const Global = typeof window !== 'undefined' ? window : global
@@ -41,14 +39,23 @@ const log = (...args) => data => {
4139
// reference: https://blog.carbonfive.com/2017/12/20/easy-pipeline-debugging-with-curried-console-log/
4240
export const Rlog = (arg = 'Rlog: ') => R.tap(log(arg))
4341

44-
export const cutFrom = (val, cutnumber = 20) => {
45-
if (nilOrEmpty(val)) {
46-
return ''
47-
}
48-
if (val.length <= cutnumber) {
49-
return val
50-
}
51-
return `${R.slice(0, cutnumber, val)} ...`
42+
/**
43+
* cut extra length of a string
44+
* 截取固定长度字符串,并添加省略号(...)
45+
* @param {*string} str 需要进行处理的字符串,可含汉字
46+
* @param {*number} len 需要显示多少个汉字,两个英文字母相当于一个汉字
47+
*/
48+
export const cutFrom = (str, len = 20) => {
49+
const reg = /[\u4e00-\u9fa5]/g // 匹配中文
50+
const slice = str && str.substring(0, len)
51+
// eslint-disable-next-line no-bitwise
52+
const chineseCharNum = ~~(
53+
slice &&
54+
slice.match(reg) &&
55+
slice.match(reg).length
56+
)
57+
const realen = slice && slice.length * 2 - chineseCharNum
58+
return str && str.substr(0, realen) + (realen < str.length ? '...' : '')
5259
}
5360

5461
// https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip

0 commit comments

Comments
 (0)