如何测试 RegEx 是否匹配字符串完全?
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
最佳答案
事先修改模式,使其只匹配整个字符串:
var r = /^a$/
或者检查之后模式是否匹配整个字符串:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
关于javascript - 使用 JavaScript 匹配精确的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/447250/