-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathhighlight.js
More file actions
34 lines (28 loc) · 990 Bytes
/
highlight.js
File metadata and controls
34 lines (28 loc) · 990 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import './highlight.less'
const escapeRegExp = (value) => {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
const escapeHtml = (value) => {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
const sanitizeClassName = (value) => {
const className = value ? `${value}` : 'ops-text-highlight'
return /^[A-Za-z0-9_-]+$/.test(className) ? className : 'ops-text-highlight'
}
const highlight = (el, binding) => {
const options = (binding && binding.value) || {}
if (options.value === undefined || options.value === null || `${options.value}` === '') {
return
}
const text = escapeHtml(el.innerText || '')
const keyword = escapeRegExp(`${options.value}`)
const className = sanitizeClassName(options.class)
const regex = new RegExp(`(${keyword})`, 'gi')
el.innerHTML = text.replace(regex, `<span class='${className}'>$1</span>`)
}
export default highlight