|
1 | 1 | import './highlight.less' |
2 | 2 |
|
| 3 | +const escapeRegExp = (value) => { |
| 4 | + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 5 | +} |
| 6 | + |
| 7 | +const escapeHtml = (value) => { |
| 8 | + return value |
| 9 | + .replace(/&/g, '&') |
| 10 | + .replace(/</g, '<') |
| 11 | + .replace(/>/g, '>') |
| 12 | + .replace(/"/g, '"') |
| 13 | + .replace(/'/g, ''') |
| 14 | +} |
| 15 | + |
| 16 | +const sanitizeClassName = (value) => { |
| 17 | + const className = value ? `${value}` : 'ops-text-highlight' |
| 18 | + return /^[A-Za-z0-9_-]+$/.test(className) ? className : 'ops-text-highlight' |
| 19 | +} |
| 20 | + |
3 | 21 | const highlight = (el, binding) => { |
4 | | - if (binding.value.value) { |
5 | | - let testValue = `${binding.value.value}` |
6 | | - if (['(', ')', '$'].includes(testValue)) { |
7 | | - testValue = `\\${testValue}` |
8 | | - } |
9 | | - const regex = new RegExp(`(${testValue})`, 'gi') |
10 | | - el.innerHTML = el.innerText.replace(regex, `<span class='${binding.value.class ?? 'ops-text-highlight'}'>$1</span>`) |
11 | | - } |
| 22 | + const options = (binding && binding.value) || {} |
| 23 | + if (options.value === undefined || options.value === null || `${options.value}` === '') { |
| 24 | + return |
| 25 | + } |
| 26 | + |
| 27 | + const text = escapeHtml(el.innerText || '') |
| 28 | + const keyword = escapeRegExp(`${options.value}`) |
| 29 | + const className = sanitizeClassName(options.class) |
| 30 | + const regex = new RegExp(`(${keyword})`, 'gi') |
| 31 | + el.innerHTML = text.replace(regex, `<span class='${className}'>$1</span>`) |
12 | 32 | } |
13 | 33 |
|
14 | 34 | export default highlight |
0 commit comments