karfau
(Christian Bewernitz)
1
I have an issue with a recommendation done by JavaScript static code analysis: Regular expression quantifiers and character classes should be used concisely
It suggests to replace [0-9]
with \d
, but \d
stands for [0-9.,]
(spot the dot
)
/[0-9]+/.test('0.9')
returns false
/[0-9]+/.test('0,9')
returns false
but
/\d+/.test('0.9')
returns true
/\d+/.test('0,9')
returns true
I think this recommendation is misleading, if not dangerous in case the intention is to only accept digits.
\d
is [0-9]
. With all RegExp engines I know.
I havenât worked with JS for many years, which is why I looked again. From developer.mozilla.org:
Matches any digit (Arabic numeral). Equivalent to [0-9]
.
/\d+/.test('0.9') ? alert("true") : alert("false"); // --> true
/^\d+$/.test('0.9') ? alert("true") : alert("false"); // --> false
/[0-9]+/.test('0.9') ? alert("true") : alert("false"); // --> true
/^[0-9]+$/.test('0.9') ? alert("true") : alert("false"); // --> false
I also find the rule a bit strange. You can mark it as âWontât fixâ. It is also classified as Minor.
karfau
(Christian Bewernitz)
3
Ah, you are right, I missed the part about the exact match.
Sorry for the noise.
system
(system)
Closed
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.