Alex Rivera | Logout

Matching exact string with JavaScript

Asked 2009-01-15T15:45:05.450
94

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
Edit
Report

1 Answer

41

Write your regex differently:

var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
answered 2009-01-15T15:48:57.563

Your Answer