0

I have noticed some difference in representing strings in DOM passed from server as HTML attribute or as global var.

There is a string which is JSON encoded object with special chars in it and set this string in folowing ways:

<div id="my-id"
    data-opt='[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]'
></div>

<script>
    window.opt = '[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]';
</script>

Now check them with js:

;(function(window) {
    console.log(document.getElementById('my-id').dataset.opt);
    console.log(window.opt);
}(window))

Output:

[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]

[{"id":"600900340","parent_id":"600900000","name":" Collector's Cars & Models","visible":"1","level":"3"}]

Why are they different?

Here is jsfiddle http://jsfiddle.net/9ss5M/3/

1
  • “Why are they different?” – because you use JavaScript unicode escape syntax once in a JavaScript context (window.opt), and once in an HTML context where it is taken just literally (data-opt). Commented Nov 12, 2013 at 11:50

1 Answer 1

2

Because escape sequences such as \t and \u#### that have special meanings in JavaScript strings (including JSON), are meaningless in HTML attribute values.

For what it's worth, escape sequences in HTML take the form of entity references. To wit:

<div id="my-id"
    data-opt='[{"id":"600900340","parent_id":"600900000","name":"&#9;Collector&#x0027;s Cars &#x0026; Models","visible":"1","level":"3"}]'
></div>

Updated fiddle

And of course, there's the option of inserting the special characters literally as is without resorting to escape sequences as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.