index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // @ts-nocheck
  2. /**
  3. * 计算字符串字符的长度并可以截取字符串。
  4. * @param char 传入字符串(maxcharacter条件下,一个汉字表示两个字符)
  5. * @param max 规定最大字符串长度
  6. * @returns 当没有传入maxCharacter/maxLength 时返回字符串字符长度,当传入maxCharacter/maxLength时返回截取之后的字符串和长度。
  7. */
  8. export type CharacterLengthResult = {
  9. length : number;
  10. characters : string;
  11. }
  12. // #ifdef APP-ANDROID
  13. type ChartType = any
  14. // #endif
  15. // #ifndef APP-ANDROID
  16. type ChartType = string | number
  17. // #endif
  18. export function characterLimit(type : string, char : ChartType, max : number) : CharacterLengthResult {
  19. const str = `${char}`;
  20. if (str.length == 0) {
  21. return {
  22. length: 0,
  23. characters: '',
  24. } as CharacterLengthResult
  25. }
  26. if (type == 'maxcharacter') {
  27. let len = 0;
  28. for (let i = 0; i < str.length; i += 1) {
  29. let currentStringLength : number// = 0;
  30. const code = str.charCodeAt(i)!
  31. if (code > 127 || code == 94) {
  32. currentStringLength = 2;
  33. } else {
  34. currentStringLength = 1;
  35. }
  36. if (len + currentStringLength > max) {
  37. return {
  38. length: len,
  39. characters: str.slice(0, i),
  40. } as CharacterLengthResult
  41. }
  42. len += currentStringLength;
  43. }
  44. return {
  45. length: len,
  46. characters: str,
  47. } as CharacterLengthResult
  48. } else if (type == 'maxlength') {
  49. const length = str.length > max ? max : str.length;
  50. return {
  51. length: length,
  52. characters: str.slice(0, length),
  53. } as CharacterLengthResult
  54. }
  55. return {
  56. length: str.length,
  57. characters: str,
  58. } as CharacterLengthResult
  59. };