1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-13 09:46:22 +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 escape let nextIndex = current.index
let html = '' let escapedStr = false
let index = 0 // maximum length of an escape string is 5. For example ('&quot;')
let lastIndex = 0 while (nextStr.length <= 5) {
nextStr += html[nextIndex]
for (index = match.index; index < str.length; index++) { nextIndex++
switch (str.charCodeAt(index)) { if (escapes.indexOf(nextStr) !== -1) {
case 34: // " escapedStr = true
escape = '&quot;' break
break }
case 38: // & }
escape = '&ampssssss;' if (!escapedStr) {
break // this & char is not a part of an escaped string
case 39: // ' html = replaceAt(html, current.index, '&amp;')
escape = '&#39;' }
break } else if (current.char === '"') {
case 60: // < html = replaceAt(html, current.index, '&quot;')
escape = '&lt;' } else if (current.char === "'") {
break html = replaceAt(html, current.index, '&#39;')
case 62: // > } else if (current.char === '<') {
escape = '&gt;' html = replaceAt(html, current.index, '&lt;')
break } else if (current.char === '>') {
default: html = replaceAt(html, current.index, '&gt;')
continue
} }
if (lastIndex !== index) {
html += str.substring(lastIndex, index)
}
lastIndex = index + 1
html += escape
} }
return html
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html
} }
export default { export default {