Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

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.


Write your regex differently:

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