var keys = Object.keys || function(obj) {
obj = Object(obj)
var arr = []
for (var a in obj) arr.push(a)
return arr
}
var invert = function(obj) {
obj = Object(obj)
var result = {}
for (var a in obj) result[obj[a]] = a
return result
}
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": "'"
}
}
entityMap.unescape = invert(entityMap.escape)
var entityReg = {
escape: RegExp('[' + keys(entityMap.escape).join('') + ']', 'g'),
unescape: RegExp('(' + keys(entityMap.unescape).join('|') + ')', 'g')
}
// 将HTML转义为字符实体
function escape(html:string) {
if (typeof html !== 'string') return ''
return html.replace(entityReg.escape, function(match) {
return entityMap.escape[match]
})
}
// 将字符实体转回为HTML
function unescape(str:string) {
if (typeof str !== 'string') return ''
return str.replace(entityReg.unescape, function(match) {
return entityMap.unescape[match]
})
}