Reputation: 113
I'm actually looking for a javascript function (or library) that can work like Java's java.net.URLEncoder.encode(String s, String encoding) but if that's not possible how can you encode Arabic characters into single-byte coded arabic character set like ISO-8859-6 or Windows-1256.
Upvotes: 2
Views: 2744
Reputation: 38400
Unfortunately JavaScript only supports UTF-8 encoding when using encodeURIComponent
(which strictly speaking is the correct thing to do because URL encoding with a different charset is technically possible, but not standardized).
If you want the browser to do the encoding, then (AFAIK) it's not possible with AJAX.
Browsers do it in forms with accept-charset
:
<form action="/some-url" method="get" accept-charset="ISO-8859-6">
<input name="test">
<input type="submit">
</form>
So you could generate such a form with JavaScript, submit it to an iframe
and then read it's content.
If that isn't an option, I guess you'll need to write your own URI encoder. Something like this:
var iso_8859_6_encoding = {"ء": "C1", "آ": "C2", "أ": "C3", "ؤ": "C4" /* etc. */};
function encodeURIComponentWithCharset(str, charset) {
var result = "";
for (var i = 0, len = str.length; i < len; i++) {
var char = str.charAt(i);
if (str.charCodeAt(i) < 128) {
result += encodeURIComponent(char);
} elseif (charset[char]) {
result += "%" + charset[char];
} else {
// Drop undefined chars
}
}
return result;
}
encodeURIComponentWithCharset("your string", iso_8859_6_encoding);
(Untested. Encoding from http://en.wikipedia.org/wiki/ISO-8859-6 )
Upvotes: 1