Everything seems to point that .test() is supposed to be able to test an entire string but I can't get it to work:
var exp = new RegExp("^([a-z])$");
console.log( exp.test('hello') );
console.log( /^([a-z0-9])$/.test('abc12') );
Both return false when it's supposed to be true;
here's a link to a demo: http://jsbin.com/ibokem/1/
Character classes match single characters. You need to repeat them:
var exp = new RegExp("^([a-z]*)$");
console.log( exp.test('hello') );
console.log( /^([a-z0-9]*)$/.test('abc12') );
Or if you want to require at least one character, use +
instead of *
.
Also, if you're just using the patterns with test
, you can get rid of the parentheses:
var exp = new RegExp("^[a-z]*$");
console.log( exp.test('hello') );
console.log( /^[a-z0-9]*$/.test('abc12') );