3

I have a set of JavaScript objects I bootstrap to a backend template to initialise my Backbone.js collections on page load. It looks something like this (as Twig template):

<script type="text/javascript">
(function() {
    var jobCollection = new App.Collections.Item(
        {% for item in items %}
        {
            name: '{{ item.name }}',
            ...
        },
        {% endfor %}
    );
})();
</script>

The problem I'm having is that some text fields contain \u200b (Zero width space) that break the JavaScript.

What is the best way to escape these characters? Should I escape them in the backend (I'm using Symfony 2 with Twig to render the initial template) or should I escape them on the client with JavaScript? How can I escape the zero width space character and others in JavaScript or PHP?

wowpatrick
  • 5,082
  • 15
  • 55
  • 86

1 Answers1

3

If the character only appears inside strings, either escaped as \u200b or as literals, you should be fine. They're only illegal as identifiers. And even as identifiers, you could still use them as object property names, if you use subscript notation (obj["aaa\u200b"] = "foo"); at least in Chrome, but I'm not sure how safe/compatible that is.

Look at a few example that seem to work:

var escaped = "aaa \u200b bbb";
var unescaped = "bbb ​ ccc";

console.log(escaped.charCodeAt(4));
console.log(unescaped.charCodeAt(4));

var obj = {};
obj[escaped] = "foo";
obj[unescaped] = "bar";
console.log(obj[escaped]);
console.log(obj[unescaped]);
console.log(obj["aaa \u200b bbb"]);
console.log(obj["bbb ​ ccc"]);

http://codepen.io/anon/pen/JqjEK

You might also be interested on this Q/A I wrote a while ago: No visible cause for "Unexpected token ILLEGAL"

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • Thanks for the gerate answer! I found out the there also was a line break in the string I set for `name` and directly afterwards was the Escape \u200b causing the errors. So I actually have to escape for line breaks, not the Escape character as you explained in the answer. – wowpatrick Feb 01 '13 at 13:14
  • Makes sense, glad you're able to figure it out! – bfavaretto Feb 01 '13 at 17:50