A
A
Andrey Ishchenko2014-03-31 14:29:36
JavaScript
Andrey Ishchenko, 2014-03-31 14:29:36

Why does RegExp get wrong result in javascript?

There is such code for checking a string (letters and numbers):
var r = new RegExp("[A-Za-z0-9]+");
r.test("abc"); //true
r.test("abc");//false
But r.test("^#$s") -true , although there are extra non-alphabetic characters in the string
How can I change the regular expression so that it checks correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nowm, 2014-03-31
@sepo

r.test("abc"), by the way, will also show true. Your regular expression is written in such a way that it returns true if the string contains at least one character from [A-Za-z0-9], but it does not prohibit the use of the rest except for the allowed characters. If there is at least one allowed character in the heap of unresolved characters, it will return true. It is necessary to add the characters of the beginning and end of the line along the edges of the regular expression:
var r = new RegExp("^[A-Za-z0-9]+$");

K
Kirill Popolov, 2014-03-31
@ezhikov

[A-Za-zA-YaYoa-yayo0-9]+

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question