Last active
April 29, 2016 14:59
-
-
Save chRyNaN/270c2761bb6c6642fd7e66df53013465 to your computer and use it in GitHub Desktop.
JavaScript code that parses HTML/XHTML escape characters
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
(function(){ | |
/** | |
* Code is heavily influenced from Underscore.js (their escape and unescape functions): | |
* https://github.com/jashkenas/underscore/blob/master/underscore.js | |
*/ | |
window.Code = {}; | |
var escapeMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''', | |
'`': '`' | |
}; | |
var unescapeMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
''': "'", | |
'`': '`' | |
}; | |
var getKeys = function(obj){ | |
if(Object.keys){ | |
return Object.keys(obj); | |
} | |
var keys = []; | |
for (var key in obj) if (obj.hasOwnProperty(key)) keys.push(key); | |
return keys; | |
}; | |
var createEscaper = function(map){ | |
var escaper = function(match){ | |
return map[match]; | |
} | |
var source = '(?:' + getKeys(map).join('|') + ')'; | |
var testRegexp = RegExp(source); | |
var replaceRegexp = RegExp(source, 'g'); | |
return function(string){ | |
string = string == null ? '' : '' + string; | |
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; | |
}; | |
}; | |
var cEscape = createEscaper(escapeMap); | |
var cUnescape = createEscaper(unescapeMap); | |
var escapeCodeTag = function(string){ | |
var startIndex = string.indexOf('<code>'); | |
if(startIndex != -1){ | |
var endIndex = string.indexOf('</code>'); | |
if(endIndex == -1 || endIndex < startIndex) return string; | |
string = string.substring(startIndex, endIndex - startIndex); | |
string = cEscape(string); | |
} | |
return string; | |
}; | |
window.Code.tagEscape = cEscape; | |
window.Code.tagUnescape = cUnescape; | |
window.Code.escapeCodeTag = escapeCodeTag; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment