Learn how to easily deal with this JavaScript syntax error.

How to handle JavaScript Syntax Error: The only valid numeric escape in strict mode is '\0'

As I was working on a new feature of an application that should allow the user to provide a filename to create in the system, I had to implement a validator that should check whether the string contains special characters that aren't allowed in filenames. The implementation is the following one with JavaScript:

function isFilenameValid(filename){
    return !(new RegExp("[<>:/\\|?*\"]|[\0-\31]").test(filename) || filename.length > 255);
}

And it works quite well as I tested it with the common cases in the sandbox, so I included in the project. However, on the runtime of my Vue project, the mentioned exception showed up.

What causes the error

The code that triggers the exception is probably running on strict mode. You can verify this if somewhere in your code, there's a plain string that specified the use of strict mode:

// Whole-script strict mode syntax
'use strict';

When using the Strict Mode:

  • Octal numeric literals are not allowed
  • Escape characters are not allowed

Other exceptions that you may find when using the strict mode when using code like this:

"use strict";
var a = "\300";

var b = "\00a0\00a0";

Are the following ones:

SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge)
SyntaxError: "0"-prefixed octal literals and octal escape  sequences are deprecated; for octal literals use the "0o" prefix instead

For more information about the strict mode, check out the reference on MDN.

Solution

You need to escape the literal characters that are causing the trouble. For example, in the method that I used to validate the filename, there's a regular expression that contains 2 unescaped numeric literals (0 and 31), to fix the issue it's necessary to escape it (prepend double inverted slash before the numeric literal [\\0-\\31]). The regexp with the solution would now look like this:

function isFilenameValid(filename){
    return !(new RegExp("[<>:/\\|?*\"]|[\\0-\\31]").test(filename) || filename.length > 255);
}

The same would work with the other examples:

"use strict";
var a = "\\300";

var b = "\\00a0\\00a0";

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors