I’m using javascript’s inbuilt .test() function to test whether a string or regex matches. I took the regex from RegexLib, so I know that it matches the string it’s tested against (in this case joe@aol.com), however it either returns false or nothing at all.
Here’s my code:
var string = "joe@aol.com";
var pattern = [\w-]+@([\w-]+\.)+[\w-]+/i;
var match = pattern.test(string);
document.write(match);
When the regex is encased in quotes, the test returns false, when it’s not encased in anything, it returns nothing.
What I’ve tried so far:
- Simply using a single line,
var match = '[\w-]+@([\w-]+\.)+[\w-]+/i'.test("joe@aol.com");. - Using both
'single quotes and"double quotes for bothregexandstring. - Appending the regex with
/iand/g.
I honestly don’t know what’s causing this issue, so any help would be great. It could be a complete rookie mistake, a forgotten syntax perhaps.
Here’s a link to the jsFiddle I made up for you to play around with if you think you’ve got some idea of how to fix this up: http://jsfiddle.net/wFhEJ/1/
You missed the opening slash for a regexp. The notation for a regexp is:
What happened with enclosing the regexp is that it became a string, and on jsFiddle
String.prototype.testhas been set by MooTools. MooTools seems to provide aString.prototype.testfunction, but it’s not the same asRegExp.prototype.test.http://jsfiddle.net/wFhEJ/2/
Do note though that
document.writeis frowned upon. You might rather wantdocument.body.appendChild(document.createTextNode(match))or something alike.