utils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // 获取字节长度,中文算2个字节
  2. function getStrLen(str) {
  3. // eslint-disable-next-line no-control-regex
  4. return str.replace(/[^\x00-\xff]/g, 'aa').length
  5. }
  6. // 截取指定字节长度的子串
  7. function substring(str, n) {
  8. if (!str) return ''
  9. const len = getStrLen(str)
  10. if (n >= len) return str
  11. let l = 0
  12. let result = ''
  13. for (let i = 0; i < str.length; i++) {
  14. const ch = str.charAt(i)
  15. // eslint-disable-next-line no-control-regex
  16. l = /[^\x00-\xff]/i.test(ch) ? l + 2 : l + 1
  17. result += ch
  18. if (l >= n) break
  19. }
  20. return result
  21. }
  22. function getRandom(max = 10, min = 0) {
  23. return Math.floor(Math.random() * (max - min) + min)
  24. }
  25. function getFontSize(font) {
  26. const reg = /(\d+)(px)/i
  27. const match = font.match(reg)
  28. return (match && match[1]) || 10
  29. }
  30. function compareVersion(v1, v2) {
  31. v1 = v1.split('.')
  32. v2 = v2.split('.')
  33. const len = Math.max(v1.length, v2.length)
  34. while (v1.length < len) {
  35. v1.push('0')
  36. }
  37. while (v2.length < len) {
  38. v2.push('0')
  39. }
  40. for (let i = 0; i < len; i++) {
  41. const num1 = parseInt(v1[i], 10)
  42. const num2 = parseInt(v2[i], 10)
  43. if (num1 > num2) {
  44. return 1
  45. } else if (num1 < num2) {
  46. return -1
  47. }
  48. }
  49. return 0
  50. }
  51. module.exports = {
  52. getStrLen,
  53. substring,
  54. getRandom,
  55. getFontSize,
  56. compareVersion
  57. }