Escape \\\​(零宽度空格)等非法JavaScript字符 [英] Escape \u200b (Zero width space) and other illegal JavaScript characters

查看:149
本文介绍了Escape \\\​(零宽度空格)等非法JavaScript字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组JavaScript对象,我引导到后端模板,以便在页面加载时初始化我的Backbone.js集合。它看起来像这样(如Twig模板):

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

我遇到的问题是一些文本字段包含\\\​(零宽度空间)打破JavaScript。



逃避这些角色的最好方法是什么?我应该在后台逃脱(我使用Symfony 2和Twig来渲染初始模板),还是应该用JavaScript在客户端上逃避他们?如何避免使用JavaScript或PHP中的零宽度空格字符?

解决方案

如果字符只出现在字符串内,转义为 \\\​ 或作为文字,你应该没事。它们只是非法的标识符。甚至作为标识符,如果使用下标符号( obj [aaa\\\​] =foo),您仍然可以将其用作对象属性名称;至少在Chrome中,但我不知道这是多么安全/兼容。



看看似乎有效的几个例子:

  var escaped =aaa \\\​ 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 \\\​ bbb]);
console.log(obj [bbb ccc]);

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



您可能也会对此Q / AI写一段时间感兴趣之前:意外令牌ILLEGAL的明显原因


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?

解决方案

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"

这篇关于Escape \\\​(零宽度空格)等非法JavaScript字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆