合同小程序前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.6 KiB

  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. };