Javascript parse error on ‘\u2028’ unicode character

Yes, it’s a feature of the JavaScript language, documented in the ECMAScript standard (3rd edition section 7.3), that the U+2028 and U+2029 characters count as line endings. Consequently a JavaScript parser will treat any unencoded U+2028/9 character in the same way as a newline. Since you can’t put a newline inside a string literal, you get a syntax error.

This is an unfortunate oversight in the design of JSON: it is not actually a proper subset of JavaScript. Raw U+2028/9 characters are valid in string literals in JSON, and will be accepted by JSON.parse, but not so in JavaScript itself.

Hence it is only safe to generate JavaScript code using a JSON parser if you’re sure it explicitly \u-escapes those characters. Some do, some don’t; many \u-escape all non-ASCII characters, which avoids the problem.

Leave a Comment