string.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * 字符串方法的扩展
  3. *
  4. * @author lautin
  5. * @created 2019-11-22 15:24:20
  6. */
  7. /**
  8. * 生成一组随机值的方法,用于上传文件名等场景
  9. * @param {number} len
  10. */
  11. function random(count = null) {
  12. let len = count || 32,
  13. $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
  14. ret = '',
  15. time = new Date().getTime().toString();
  16. if (len / 2 > time.length) {
  17. // 控制总长度不超出
  18. len = len - time.length
  19. } else {
  20. len = len / 2
  21. }
  22. for (let i = 0; i < len; i++) {
  23. ret += $chars.charAt(Math.floor(Math.random() * $chars.length))
  24. if (time[i]) {
  25. ret += time[time.length - i - 1]
  26. }
  27. }
  28. return ret;
  29. }
  30. /**
  31. * 截取字符串之前之后
  32. * @param {string} str
  33. * @param {string} targe
  34. * @param {number} index
  35. */
  36. function getCaptionLength(str, targe, index) {
  37. if (!index) {
  38. return str.substring(0, str.indexOf(targe))
  39. } else {
  40. return str.substring(str.lastIndexOf(targe) + 1)
  41. }
  42. }
  43. // 绑定为静态方法
  44. Object.assign(String, {
  45. random,
  46. getCaptionLength
  47. });
  48. // fontcolor设置别名
  49. String.prototype.color = Object.prototype.fontcolor;
  50. export default {
  51. random,
  52. getCaptionLength
  53. }