123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /**
- * 通用关键字高亮替换
- * @param {String} value 要高亮的字符串
- * @param {String|Array} oldChar 要被替换的字符串(或数组)
- * @param {String|Array} newChar 要替换成的字符串(或数组)
- *
- * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` 高亮
- * 则此时 value -> `剑鱼标讯工具函数`
- * oldChar -> `工具`
- * newChar -> `<span class="highlight-text">工具</span>`
- *
- * 批量高亮-----
- * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` `剑鱼` 高亮
- * 则此时 value -> `剑鱼标讯工具函数`批量高亮
- * oldChar -> ['工具', '剑鱼']
- * newChar -> ['<span class="highlight-text">', '</span>']
- *
- * 注意:此时newChar为一个长度为2的数组,数组中为高亮标签的起始标签和结束标签
- *
- */
- export function replaceKeyword(
- value,
- oldChar,
- newChar = ['<span class="highlight-text">', '</span>']
- ) {
- if (!oldChar || !newChar) return value
- // oldChar的字符串数组
- let oldCharArr = []
- if (Array.isArray(oldChar)) {
- oldCharArr = oldChar.concat()
- } else {
- oldCharArr.push(oldChar)
- }
- // 数组去重
- oldCharArr = Array.from(new Set(oldCharArr))
- for (let i = 0; i < oldCharArr.length; i++) {
- if (!oldCharArr[i]) {
- continue
- } else {
- oldCharArr[i] = oldCharArr[i]
- .replace(/([$()*+.[\]?/\\^{}|])/g, '\\$1')
- .replace(/\s+/g, '')
- }
- }
- // 数组去空
- const lastArr = oldCharArr
- .filter((item) => !!item)
- .sort((a, b) => b.length - a.length)
- const regExp = new RegExp(`(${lastArr.join('|')})`, 'gmi')
- if (lastArr.length === 0) {
- return value
- }
- if (Array.isArray(newChar)) {
- // 批量高亮
- return value.replace(regExp, newChar.join('$1'))
- } else {
- // 普通单个高亮
- return value.replace(regExp, newChar)
- }
- }
- /**
- * 从key=value&key1=value1&key2=value2...中获取key值
- * @param {String} formString 目标字符串,必须为key=value&key1=value1的格式
- * @param {String} targetKey 要从目标字符串获取哪个key
- * @returns {String}
- */
- export function getFormValue(formString, targetKey) {
- let reg = new RegExp('(^|&)' + targetKey + '=([^&]*)(&|$)', 'i')
- let r = formString.match(reg) //获取url中'?'符后的字符串并正则匹配
- let context = ''
- if (r != null) context = r[2]
- // 释放变量
- reg = null
- r = null
- return context == null || context == '' || context == 'undefined' ? '' : context
- }
- /**
- * 从url中获取对应name的参数
- * @param {String} name
- * @returns {String}
- */
- export function getQueryParam(name) {
- const search = window.location.search
- let target = ''
- if (search) {
- const arr = search.split('?')
- if (arr[1]) {
- target = arr[1]
- }
- }
- const value = getFormValue(target, name)
- return decodeURIComponent(value)
- }
|