Skip to content

Instantly share code, notes, and snippets.

@tinganho
Created July 16, 2015 08:36
Show Gist options
  • Save tinganho/cb1b38d4adade16aa492 to your computer and use it in GitHub Desktop.
Save tinganho/cb1b38d4adade16aa492 to your computer and use it in GitHub Desktop.
export namespace Html {
let charToEntityRegex: RegExp;
let entityToCharRegex: RegExp;
let charToEntity: Map = {};
let entityToChar: Map = {
'&': '&',
'>': '>',
'&lt;': '<',
'&quot;': '"',
'&#39;': '\''
}
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