JSLint "insecure ^" in regular expression
Asked Answered
S

3

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, '');
Shrubby answered 5/11, 2010 at 19:10 Comment(5)
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).Retrogression
FWIW, you don't need to escape the - where you have it.Incumbency
@Robusto, explicitly escaping hyphens in character classes is another JSLint recommendation.Kinsley
See also JSLint reports “Insecure ^” for my regex — what does that mean?Monjo
There are also performance issues with negation.Stainless
L
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.

Licketysplit answered 5/11, 2010 at 19:17 Comment(4)
Blergh, is JSLint not smart enough to see that I'm replacing everything but those things? string.match(/[\w,\-]/g, '').join('') it is, then.Shrubby
@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.Gentilesse
Complaining about JSLint's over-strictness is a pastime of consummate professionals the world over.Walcott
you don't want to know the truth about jslint....Because you can't handle the truth!Parcenary
H
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/

Harbot answered 24/6, 2014 at 4:4 Comment(0)
C
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.

Comfy answered 30/10, 2013 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.