M.SH
M.SH

Reputation: 378

unicode to utf-8 in JavaScript

i have output from a server like

["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"]

i want to convert it like ["alex", "to its right language"] using js or jquery

i tried

function encode_utf8( s )
{
   return unescape( encodeURIComponent( s ) )
}

but not working correctly

any help?
thanks in advance

Upvotes: 4

Views: 5554

Answers (1)

Tobias Krogh
Tobias Krogh

Reputation: 3932

I am not sure about what you mean by getting output "LIKE" the shown example...

but if you get ["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"] and assign it to a variable like

var foo = ["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"];
// alert(foo[1]) results in "��������" which actually means
// the engine has at least tried to resolve the characters

for example if you pass in correct character codes like:

var foo = ["alex", "\u003cp\u003emy UTF paragraph\u003c/p\u003e"];
// alert(foo[1]) results in "<p>my UTF paragraph</p>" which seems correct to me...

Try the examples above in a browser console (works at least for me in current Chrome)

On the other hand if you receive "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd" every time then I assume similar to the commentors that your response already gets messed up before you are handling it in JavaScript

This article shows nicely that using Unicode characters is valid for variable naming so the same should apply to string content.

Upvotes: 1

Related Questions