Why isn’t my code around the test function in Object RegExp working the same way as the regex pattern. Am I missing something or Am I using the wrong escape regex
<html>
<body>
<script type="text/javascript">
var str = "info@test.com";
//This isn't working
var regStr = "^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$"; //This string can be any regex get from XSLT
//Escape function get from: http://stackoverflow.com/a/6969486/193850
regStr = regStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
console.log(regStr); // \^\(\[w\-\]\+\(\?:\.\[w\-\]\+\)\*\)@\(\(\?:\[w\-\]\+\.\)\*w\[w\-\]\{0,66\}\)\.\(\[a\-z\]\{2,6\}\(\?:\.\[a\-z\]\{2\}\)\?\)\$
var re = new RegExp(regStr , "i");
console.log(re.test(str)); //false
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
console.log(filter.test(str)); //true
</script>
</body>
</html>
See, there’s a confusion. The function you’ve used is a nice way of preprocessing your string-to-be regexes so you don’t have to worry about escaping regex metacharacters – i.e., symbols that will control the regex behaviour, and not just taken literally.
But the point is that your string has already been parsed before it was taken by this escaping function:
\wand\.sequences became justwand.respectively, the preceding slash was lost.The escaper function, actually, did restore the slash before the
., butwwasn’t special for it in any kind. ) Therefore the string that went into RegExp constructor had[w]instead of[\w].It’s actually quite easy to check: just
console.log(regStr)after the replacement operation.