Bkjain655
Bkjain655

Reputation: 200

RegExp not matching results

I am trying to match a pattern in javascript.

Following is the example:

var pattern = "/^[a-z0-9]+$/i"; // This is should accept on alpha numeric characters.
var reg = new RegExp(pattern);
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

When i run this I am getting both the results as false. I do think that I am missing something simple. But little bit confused.

Thanks in advance.

Upvotes: 1

Views: 30

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Your pattern is wrong. You don't need to use RegExp constructor here. And you need either ingnore case flag or add uppercase letters to range.

var reg = /^[a-zA-Z0-9]+$/;
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

Upvotes: 0

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

You need not use slashes if you are using RegExp constructor. You either use enclosing slashes without double quotes to denote a regular expression or you pass a string (usually enclosed in quotes) to RegExp constructor:

var pattern = "^[a-z0-9]+$"; // This is should accept on alpha numeric characters.
var reg = new RegExp(pattern, "i");
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

Upvotes: 2

Related Questions