utils.js 824 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * 获取字符串长度,英文字符 长度1,中文字符长度2
  3. * @param {*} str
  4. */
  5. export const getStrFullLength = (str = '') =>
  6. str.split('').reduce((pre, cur) => {
  7. const charCode = cur.charCodeAt(0)
  8. if (charCode >= 0 && charCode <= 128) {
  9. return pre + 1
  10. }
  11. return pre + 2
  12. }, 0)
  13. /**
  14. * 截取字符串,根据 maxLength 截取后返回
  15. * @param {*} str
  16. * @param {*} maxLength
  17. */
  18. export const cutStrByFullLength = (str = '', maxLength) => {
  19. let showLength = 0
  20. return str.split('').reduce((pre, cur) => {
  21. const charCode = cur.charCodeAt(0)
  22. if (charCode >= 0 && charCode <= 128) {
  23. showLength += 1
  24. } else {
  25. showLength += 2
  26. }
  27. if (showLength <= maxLength) {
  28. return pre + cur
  29. }
  30. return pre
  31. }, '')
  32. }