views:

535

answers:

3

How can I test if a regex matches a string exactly?

var r = /a/;
r.test("a"); // returns true
r.test("ba"); // returns true
testExact(r, "ba"); // should return false
testExact(r, "a"); // should return true
+6  A: 

either

var r = /^.$/

or

function matchExact(r, str) { 
   return str === str.match(r);
}
Jimmy
+1  A: 

Write your regex differently:

var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
Prestaul
A: 

If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?

If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.

Svante