Reputation: 200
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
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
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