str.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * 通用关键字高亮替换
  3. * @param {String} value 要高亮的字符串
  4. * @param {String|Array} oldChar 要被替换的字符串(或数组)
  5. * @param {String|Array} newChar 要替换成的字符串(或数组)
  6. *
  7. * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` 高亮
  8. * 则此时 value -> `剑鱼标讯工具函数`
  9. * oldChar -> `工具`
  10. * newChar -> `<span class="highlight-text">工具</span>`
  11. *
  12. * 批量高亮-----
  13. * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` `剑鱼` 高亮
  14. * 则此时 value -> `剑鱼标讯工具函数`批量高亮
  15. * oldChar -> ['工具', '剑鱼']
  16. * newChar -> ['<span class="highlight-text">', '</span>']
  17. *
  18. * 注意:此时newChar为一个长度为2的数组,数组中为高亮标签的起始标签和结束标签
  19. *
  20. */
  21. export function replaceKeyword(
  22. value,
  23. oldChar,
  24. newChar = ['<span class="highlight-text">', '</span>']
  25. ) {
  26. if (!oldChar || !newChar) return value
  27. // oldChar的字符串数组
  28. let oldCharArr = []
  29. if (Array.isArray(oldChar)) {
  30. oldCharArr = oldChar.concat()
  31. } else {
  32. oldCharArr.push(oldChar)
  33. }
  34. // 数组去重
  35. oldCharArr = Array.from(new Set(oldCharArr))
  36. for (let i = 0; i < oldCharArr.length; i++) {
  37. if (!oldCharArr[i]) {
  38. continue
  39. } else {
  40. oldCharArr[i] = oldCharArr[i]
  41. .replace(/([$()*+.[\]?/\\^{}|])/g, '\\$1')
  42. .replace(/\s+/g, '')
  43. }
  44. }
  45. // 数组去空
  46. const lastArr = oldCharArr
  47. .filter((item) => !!item)
  48. .sort((a, b) => b.length - a.length)
  49. const regExp = new RegExp(`(${lastArr.join('|')})`, 'gmi')
  50. if (lastArr.length === 0) {
  51. return value
  52. }
  53. if (Array.isArray(newChar)) {
  54. // 批量高亮
  55. return value.replace(regExp, newChar.join('$1'))
  56. } else {
  57. // 普通单个高亮
  58. return value.replace(regExp, newChar)
  59. }
  60. }
  61. /**
  62. * 从key=value&key1=value1&key2=value2...中获取key值
  63. * @param {String} formString 目标字符串,必须为key=value&key1=value1的格式
  64. * @param {String} targetKey 要从目标字符串获取哪个key
  65. * @returns {String}
  66. */
  67. export function getFormValue(formString, targetKey) {
  68. let reg = new RegExp('(^|&)' + targetKey + '=([^&]*)(&|$)', 'i')
  69. let r = formString.match(reg) //获取url中'?'符后的字符串并正则匹配
  70. let context = ''
  71. if (r != null) context = r[2]
  72. // 释放变量
  73. reg = null
  74. r = null
  75. return context == null || context == '' || context == 'undefined' ? '' : context
  76. }
  77. /**
  78. * 从url中获取对应name的参数
  79. * @param {String} name
  80. * @returns {String}
  81. */
  82. export function getQueryParam(name) {
  83. const search = window.location.search
  84. let target = ''
  85. if (search) {
  86. const arr = search.split('?')
  87. if (arr[1]) {
  88. target = arr[1]
  89. }
  90. }
  91. const value = getFormValue(target, name)
  92. return decodeURIComponent(value)
  93. }