1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-16 11:15:12 +00:00

updated new escape html function

This commit is contained in:
Nguyễn Việt Hưng
2018-07-04 13:50:05 +07:00
parent 0ae1263d9d
commit c2f0147cff

View File

@@ -6,52 +6,45 @@ export function lastFindInArray (array, callback) {
} }
} }
export function escapeHtmlCharacters (text) { function escapeHtmlCharacters (html) {
const matchHtmlRegExp = /["'&<>]/ const matchHtmlRegExp = /["'&<>]/g
const str = '' + text const escapes = ['&quot;', '&amp;', '&#39;', '&lt;', '&gt;']
const match = matchHtmlRegExp.exec(str) let match = null
const replaceAt = (str, index, replace) =>
str.substr(0, index) +
replace +
str.substr(index + replace.length - (replace.length - 1))
if (!match) { while ((match = matchHtmlRegExp.exec(html)) != null) {
return str const current = { char: match[0], index: match.index }
if (current.char === '&') {
let nextStr = ''
let nextIndex = current.index
let escapedStr = false
// maximum length of an escape string is 5. For example ('&quot;')
while (nextStr.length <= 5) {
nextStr += html[nextIndex]
nextIndex++
if (escapes.indexOf(nextStr) !== -1) {
escapedStr = true
break
} }
let escape
let html = ''
let index = 0
let lastIndex = 0
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '&quot;'
break
case 38: // &
escape = '&ampssssss;'
break
case 39: // '
escape = '&#39;'
break
case 60: // <
escape = '&lt;'
break
case 62: // >
escape = '&gt;'
break
default:
continue
} }
if (!escapedStr) {
if (lastIndex !== index) { // this & char is not a part of an escaped string
html += str.substring(lastIndex, index) html = replaceAt(html, current.index, '&amp;')
} }
} else if (current.char === '"') {
lastIndex = index + 1 html = replaceAt(html, current.index, '&quot;')
html += escape } else if (current.char === "'") {
html = replaceAt(html, current.index, '&#39;')
} else if (current.char === '<') {
html = replaceAt(html, current.index, '&lt;')
} else if (current.char === '>') {
html = replaceAt(html, current.index, '&gt;')
} }
}
return lastIndex !== index return html
? html + str.substring(lastIndex, index)
: html
} }
export default { export default {