43

JSLint reports Insecure '^' for the following line. Why is that? Or is it just going to complain any time I want to negate a character class?

// remove all non alphanumeric, comma and dash characters
"!$7s-gd,&j5d-a#".replace(/[^\w,\-]/g, '');
Thomas R
  • 3,026
  • 5
  • 32
  • 31
  • 1
    Because it's JSLint :p Possibly the negation could be viewed as "accepting too much" including funny [unicode] control characters (it can only guess at the regex, it doesn't know it semantically). –  Nov 05 '10 at 19:14
  • 1
    FWIW, you don't need to escape the - where you have it. – Robusto Nov 05 '10 at 19:17
  • 1
    @Robusto, explicitly escaping hyphens in character classes is another JSLint recommendation. – Ian Mackinnon Oct 16 '12 at 14:35
  • See also [JSLint reports “Insecure ^” for my regex — what does that mean?](http://stackoverflow.com/questions/3039955/jslint-reports-insecure-for-my-regex-what-does-that-mean) – Bergi Jul 31 '13 at 01:13
  • There are also performance issues with negation. – Ron Wertlen Oct 17 '13 at 19:03

3 Answers3

38

It only will do this if you have the option selected at the bottom:

Disallow insecure . and [^...] in /RegExp/

From the docs:

true if . and [^...] should not be allowed in RegExp literals. These forms should not be used when validating in secure applications.

So the answer your question, if you start a regex with ^ and it's checked, yes it'll throw the error every time. The issue is with unicode characters, you're allowing pretty much anything in there and there's potential for security issues, or validation bypassing issues. Instead of disallowing something (which can be bypassed), allow only what characters are valid.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 3
    Blergh, is JSLint not smart enough to see that I'm replacing everything *but* those things? string.match(/[\w,\-]/g, '').join('') it is, then. – Thomas R Nov 05 '10 at 19:25
  • 15
    @Tom JSLint doesn't *care* what you're doing it just offers recommendations and best practices to keep novice JavaScripter's from making foolish mistakes. If you can justify what you're doing by all means, do it, but don't complain that JSList doesn't like it. – xj9 Nov 05 '10 at 19:32
  • 18
    Complaining about JSLint's over-strictness is a pastime of consummate professionals the world over. – ErikE Jul 07 '11 at 01:12
  • 4
    you don't want to know the truth about jslint....Because you can't handle the truth! –  Aug 23 '12 at 22:07
6

regexp: true

in your lint options, will allow

. and [^...] in /RegExp/

you can configure the rules you would like to use here

http://www.jslint.com/

David Morrow
  • 8,965
  • 4
  • 29
  • 24
0

Consider using \W instead of /^\w/

"!$7s-gd,&j5d-a#".replace(/\W/g, '');

For your particular case this would not work because you want to leave comma and dash characters, but I think it is worth mentioning.

dugokontov
  • 4,402
  • 1
  • 25
  • 25