SyntaxError: illegal character - JavaScript 编辑

The JavaScript exception "illegal character" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code.

Message

SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)

Error type

SyntaxError

What went wrong?

There is an invalid or unexpected token that doesn't belong at this position in the code. Use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash () or simple quotes ( " ) vs non-standard quotation marks ().

Examples

Mismatched characters

Some characters look similar, but will cause the parser to fail interpreting your code. Famous examples of this are quotes, the minus or semicolon (greek questionmark (U+37e) looks same).

“This looks like a string”;  // SyntaxError: illegal character
                             // “ and ” are not " but look like this

42 – 13;                     // SyntaxError: illegal character
                             // – is not - but looks like this

var foo = 'bar';             // SyntaxError: illegal character
                             // <37e> is not ; but looks like this

This should work:

"This is actually a string";
42 - 13;
var foo = 'bar';

Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.

Forgotten characters

It's easy to forget a character here or there.

var colors = ['#000', #333', '#666'];
// SyntaxError: illegal character

Add the missing quote for '#333'.

var colors = ['#000', '#333', '#666'];

Hidden characters

When copy pasting code from external sources, there might be invalid characters. Watch out!

var foo = 'bar';
// SyntaxError: illegal character

When inspecting this code in an editor like Vim, you can see that there is actually a zero-width space (ZWSP) (U+200B) character.

var foo = 'bar';<200b>

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:71 次

字数:3946

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文