2

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?

Mevia
  • 1,517
  • 1
  • 16
  • 51
  • what is the expected output for `test('hi')` or `test('')` ? – Kos Mar 28 '17 at 09:23
  • I don't understand this question? `°` is the HTML symbol for the degree symbol. Obviously putting this into HTML will show the degree symbol, that's it's point. What exactly do you want it to do? – Liam Mar 28 '17 at 09:23
  • @Liam I understand the question is about converting a piece HTML source representing a string into the actual string – Kos Mar 28 '17 at 09:24
  • try using .textContent instead of innerHTML? – Jaromanda X Mar 28 '17 at 09:25
  • Why can't you just pass the Unicode character instead? - If you can't have you tried `°` in place of `°` – GavinBrelstaff Mar 28 '17 at 09:25

1 Answers1

4

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.

Kos
  • 70,399
  • 25
  • 169
  • 233
  • if you're getting that JSON from somewhere else and you can't change the formatting, let me know, we'll look for something else. Starting point: http://stackoverflow.com/questions/5796718/html-entity-decode or https://www.npmjs.com/package/html-entities – Kos Mar 28 '17 at 09:33
  • I went through all this, because i have access to server i will modify the stream rather then be bothered by local conversions, thank You for the hint, its far better solution ;) – Mevia Mar 28 '17 at 09:42