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
From stackoverflow
-
either
var r = /^.$/or
function matchExact(r, str) { return str === str.match(r); } -
Write your regex differently:
var r = /^a$/; r.test('a'); // true r.test('ba'); // false -
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.
0 comments:
Post a Comment