Skip to content

Instantly share code, notes, and snippets.

@AndyNovo
Last active April 21, 2016 16:51
Show Gist options
  • Save AndyNovo/7d5802e240f783cc67ff6e912b70b469 to your computer and use it in GitHub Desktop.
Save AndyNovo/7d5802e240f783cc67ff6e912b70b469 to your computer and use it in GitHub Desktop.
var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '&lt;').
replace(/>/g, '&gt;');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment