So looks like I have ran into a weird problem and was wondering whether somebody has a solution for it or am I misusing the RegExp object in javascript. I've written down a regexp which checks whether a particular value is alphanumeric or not. The function and some sample test cases are as follows
var re = new RegExp("^[a-zA-z\\d]+$");
document.writeln(re.test("a"));
document.writeln(re.test("a1234"));
document.writeln(re.test("12345a"));
document.writeln(re.test("12345"));
document.writeln(re.test("a["));
document.writeln(re.test("[]"));
document.writeln(re.test("]"));
In all the cases, it returns a true. I tried escaping the brackets in the regular exp ie var re = new RegExp("^\\\\[a-zA-z\\\\d\\\\]+$");
but then every test case returns false.
I fixed this problem by using a regex literal instead like var re = /^[a-zA-Z\\d]+$/;
. I think I could have used \\w
but the field should not contain the _
character.
Does anybody know how to fix the problem or is the RegExp object not compatible with a set of matching characters??
Thanks in advance!
The second 'z' should be 'Z'. The ascii range between Z (0x5a) and a (0x61) includes the square brackets, the caret, backquote, and underscore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.