Created
June 24, 2012 09:28
-
-
Save alanedwardes/2982618 to your computer and use it in GitHub Desktop.
Simple JS object to encode text to its unicode character references for URLs and HTML. Makes displaying text and passing data to a server super safe.
This file contains hidden or 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
///////////////// | |
// HTML EXAMPLES | |
///////////////// | |
// Encoder.html_entities("常用國字標準字體表"); "常用國字標準字體表" | |
// Encoder.html_entities("%"); "%" | |
// Encoder.html_entities("Pig: €3.99 (£6.77)"); "Pig: €3.99 (£6.77)" | |
///////////////// | |
// URL EXAMPLES | |
///////////////// | |
// Encoder.url_encode("常用國字標準字體表"); "%u5E38%u7528%u570B%u5B57%u6A19%u6E96%u5B57%u9AD4%u8868" | |
// Encoder.url_encode("%"); "%u0025" | |
// Encoder.url_encode("Pig: €3.99 (£6.77)"); "Pig%u003A%u0020%u20AC3%u002E99%u0020%u0028%u00A36%u002E77%u0029" | |
///////////////// | |
// Encodes all characters that don't match [A-Za-z0-9_-] (change the regex below to allow other safe entities like .' etc) | |
var Encoder = | |
{ | |
url_encode: function(str) | |
{ | |
return this._hexify_string(str, '%u', ''); | |
}, | |
html_entities: function(str) | |
{ | |
return this._hexify_string(str, '&#x', ';'); | |
}, | |
_zero_pad: function(input, zeros) | |
{ | |
input = input.toString(); | |
if(input.length < zeros) | |
{ | |
return new Array((zeros - input.length) + 1).join(0) + input; | |
} else return input; | |
}, | |
_hexify_string: function(str, prepend, append) | |
{ | |
var string = str.toString().split(""); | |
var result = ''; | |
for(var i = 0;i < string.length;i++) | |
{ | |
if(string[i].match(/[A-Za-z0-9_-]/)) result += string[i]; | |
else | |
{ | |
result += prepend; | |
result += this._zero_pad(string[i].charCodeAt(0).toString(16), 4).toUpperCase(); | |
result += append; | |
} | |
} | |
return result; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment