[Developers] mql_escape and UTF-8
Will Moffat
willmoffat at metaweb.com
Thu Jul 31 13:40:51 UTC 2008
Hello,
> what would really help is if you could produce some code to do the
> escaping/unescaping on some of the more popular languages.
Here are some Javascript functions which should help.
Please let me know if you find any bugs or make any improvements.
regards,
--Will
function str2key(key) {
// key may only contain letters, numbers, underscores, hyphens
return key.replace( /[^A-Za-z0-9_-]/g, _dollarEscape );
}
function key2str(str) {
//match a 4-digit hex number starting with $
return str.replace(/\$([0-9a-f]{4})/gi,function(match,hex) {
return String.fromCharCode( parseInt(hex,16 ));
});
}
function _dollarEscape(aChar) {
var hex = aChar.charCodeAt(0).toString(16).toUpperCase();
if (hex.length==1) { return "$000"+hex; }
if (hex.length==2) { return "$00" +hex; }
if (hex.length==3) { return "$0" +hex; }
if (hex.length==4) { return "$" +hex; }
return null;
}
// tests:
print(key2str('Andrew_$0022Test$0022_Martin'))
print(key2str('Gabriel_Garc$00EDa_M$00E1rquez'))
print(str2key('Béla_Szőkefalvi-Nagy'))
print(key2str('B$00E9la_Sz$0151kefalvi-Nagy'))
More information about the Developers
mailing list