Reputation: 1685
I'm trying to validate a string for only alphanumeric characters and whitespaces.
For some reason though the expression also matches strings with backslashes:
var expression = new RegExp("^[A-z0-9 ]+$");
console.log(expression.test("Hello World")); // True
console.log(expression.test("Hello\\ World")); // True.... WHY?
Why is the backslash matching this expression? How can I make it so it doesn't?
Upvotes: 1
Views: 147
Reputation: 627537
Use
var expression = /^[A-Za-z0-9 ]+$/;
The A-z
matches more than just letters: [
, \
, ]
, ^
, _
and `
.
var expression = /^[A-Za-z0-9 ]+$/;
console.log(expression.test("Hello World")); // => True
console.log(expression.test("Hello\\ World")); // => False
Upvotes: 3