Matching exact string with JavaScript

后端 未结 5 822
离开以前
离开以前 2020-11-28 10:49

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\")         


        
5条回答
  •  遥遥无期
    2020-11-28 11:39

    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];
    }
    

提交回复
热议问题