Mevia
Mevia

Reputation: 1564

UTF-8 symbol is converted when inserted to dom

I have a following problem, i am building app that uses data stream from ajax calls, the data that is coming is therefore escaped inside json string.

example: 1°Set

When i insert that data to DOM it is being converted like this: 1°Set

I dont use any libraries like jQuery, pure Javascript.

I tried to store converted name also in another place but i cannot seem to convert it manually, i tried following functions:

var test = function(str) {
    console.log(unescape(encodeURIComponent(str)) );
    console.log(decodeURIComponent(escape(str)) );
};

test('1°Set');

It stays the same, does anyone have an idea how to convert it to a DOM like version?

Upvotes: 2

Views: 683

Answers (1)

Kos
Kos

Reputation: 72319

I have a following problem, i am building app that uses data stream from ajax calls, the data that is coming is therefore escaped inside json string.

example: 1°Set

Sounds like you're having a problem because your backend serves a JSON that looks like:

{
  "something": "1°Set"
}

Instead of a string "1°Set", you're serving HTML source code that amounts to "1°Set". This looks very unnecessary. I cannot see a good reason of using HTML escaping inside JSON, unless you actually want your JSON to actually contain a part of HTML source (with formatting and everything), rather than just a string.

My suggestion: Let's keep it simple and instead serve something like:

{
  "something": "1°Set"
}

or equivalently escape it properly using JSON syntax:

{
  "something": "1\u00b0Set"
}

Now you'll JavaScript will receive a plain string that can be easily displayed, for example inside element.textContent or element.value or anywhere else. You won't even need any conversions.

Upvotes: 4

Related Questions