Basaa
Basaa

Reputation: 1685

RegExp incorrectly matches backslash

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

Use

var expression = /^[A-Za-z0-9 ]+$/;

The A-z matches more than just letters: [, \, ], ^, _ and `.

enter image description here

var expression = /^[A-Za-z0-9 ]+$/;
console.log(expression.test("Hello World"));   // => True
console.log(expression.test("Hello\\ World")); // => False

Upvotes: 3

Related Questions