Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this regex? JSLint is throwing an error

I'm trying to validate my whole script through the new JSLint, but with this:

function a() {
    'use strict';
    var string;
    string = string.replace(/\x00*/g, '');
}

It throws:

Unexpected 'x' after '\'.

string = string.replace(/\x00*/g, '');

The old version throws no errors with that. I realize that it's in beta, but I would expect that it works just as good as the old version. \x00 stands for null character, by the way.

So, is it something that changed with ECMAScript 6? Is it just a JSLint bug? Am I actually doing something wrong?

like image 308
WilliamTheBaker Avatar asked Sep 15 '25 13:09

WilliamTheBaker


1 Answers

The "A regular expression literal can be confused with '/='" error is thrown when JSLint, JSHint (prior to version 1.0.0) or ESLint encounters a regular expression literal that begins with the = character. In the following example we attempt to assign a regular expression literal to match the string "=1" to the variable x:

This error is raised to highlight a potentially confusing piece of code. Your code will run fine if you do not fix this error, but it may be confusing to others, especially at first glance to someone quickly searching through your script.

The / character is ambiguous in JavaScript. It can either signify the start or end of a regular expression literal, as it does in the example above, or it can be interpreted as the division operator. Like most of the arithmetic operators, the division operator can be combined with the assignment operator to produce a shorthand:

https://jslinterrors.com/a-regular-expression-literal-can-be-confused-with

So you need to use the RegExp constructor:

string.replace(new RegExp('\\x00*', 'g'), '');

Which outputs the same regex as the regex literal:

console.log(new RegExp('\\x00*', 'g').toString() === /\x00*/g.toString()); // true

Tip

NULL character \x00 can be shortened to \0 (MDN docs)

new RegExp('\\0*', 'g')

--

Update

@nhahtdh's answer shows that you can use /\u0000*/g literal.

like image 69
Miguel Mota Avatar answered Sep 18 '25 08:09

Miguel Mota