str-format.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import StrKit from '@/utils/str-kit'
  2. const strFilter = {
  3. /**
  4. * 功能描述:剪切字符串过滤器
  5. * 使用方式:
  6. * {{item.deviceName | cutStr(14)}}
  7. * @param value
  8. * @param len
  9. * @param placeholder
  10. * @returns {*}
  11. */
  12. cutStr (value, len, placeholder) {
  13. if (!value) {
  14. return ''
  15. }
  16. len = len || 18
  17. placeholder = placeholder || '...'
  18. let count = 0
  19. let titleLenOld = StrKit.getByteLen(value)
  20. let titleLenNew = 0 // 初始化重新构造的title的长度
  21. for (var i = 0; i < value.length; i++) {
  22. if (titleLenNew < len) {
  23. ++count
  24. if (value[i].match(/[^x00-xff]/ig) !== null) { // 全角
  25. titleLenNew += 2
  26. } else {
  27. titleLenNew += 1
  28. }
  29. } else {
  30. break
  31. }
  32. }
  33. value = value.substring(0, count) + (titleLenOld <= len ? '' : placeholder)
  34. return value
  35. },
  36. /**
  37. * 功能描述:格式化手机号码
  38. * 使用方式:
  39. * {{item.deviceName | fmtPhoneNumber}}
  40. * @param val
  41. * @returns {string|string | *}
  42. */
  43. fmtPhoneNumber (val) {
  44. val = val.replace(/[^\d]/g, '').substr(0, 11)
  45. if (val.length <= 3) {
  46. return val
  47. } else if (val.length <= 7) {
  48. val = val.replace(/(\d{3})(\d{0,4})/, '$1-$2')
  49. } else {
  50. val = val.replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1-$2-$3')
  51. }
  52. return val
  53. },
  54. // 全局安装器
  55. install (Vue) {
  56. Vue.filter('cutStr', this.cutStr)
  57. Vue.filter('fmtPhoneNumber', this.fmtPhoneNumber)
  58. }
  59. }
  60. export default strFilter