Created
July 16, 2015 08:36
-
-
Save tinganho/cb1b38d4adade16aa492 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export namespace Html { | |
let charToEntityRegex: RegExp; | |
let entityToCharRegex: RegExp; | |
let charToEntity: Map = {}; | |
let entityToChar: Map = { | |
'&': '&', | |
'>': '>', | |
'<': '<', | |
'"': '"', | |
''': '\'' | |
} | |
addEntityToCharacterMappings(entityToChar); | |
function addEntityToCharacterMappings(entityToChar: Map) { | |
let charKeys: string[] = []; | |
let entityKeys: string[] = []; | |
for (let entity in entityToChar) { | |
let char = entityToChar[entity]; | |
charToEntity[char] = entity; | |
charKeys.push(char); | |
entityKeys.push(entity); | |
} | |
charToEntityRegex = new RegExp(`(${charKeys.join('|')})`, 'g'); | |
entityToCharRegex = new RegExp(`(${entityKeys.join('|')}|&#[0-9]{1,5};)`, 'g'); | |
} | |
export function encode(value: string){ | |
return (!value) ? null : String(value).replace(charToEntityRegex, (match, capture) => { | |
return charToEntity[capture]; | |
}); | |
} | |
export function decode(value: string) { | |
return (!value) ? null : String(value).replace(entityToCharRegex, (match, capture) => { | |
return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment