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 [email protected]
), however it either returns false or nothing at all.
Here's my code:
var string = "[email protected]";
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("[email protected]");
. - Using both
'
single quotes and"
double quotes for bothregex
andstring
. - Appending the regex with
/i
and/g
.
I honestly don't know what's causing this issue, so any help would be great. It could be a plete 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: /
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 [email protected]
), however it either returns false or nothing at all.
Here's my code:
var string = "[email protected]";
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("[email protected]");
. - Using both
'
single quotes and"
double quotes for bothregex
andstring
. - Appending the regex with
/i
and/g
.
I honestly don't know what's causing this issue, so any help would be great. It could be a plete 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/wFhEJ/1/
Share Improve this question asked Dec 25, 2011 at 16:05 AvicinnianAvicinnian 1,8305 gold badges38 silver badges56 bronze badges 01 Answer
Reset to default 6You missed the opening slash for a regexp. The notation for a regexp is:
/regexp/flags
What happened with enclosing the regexp is that it became a string, and on jsFiddle String.prototype.test
has been set by MooTools. MooTools seems to provide a String.prototype.test
function, but it's not the same as RegExp.prototype.test
.
http://jsfiddle/wFhEJ/2/
var string = "[email protected]";
var pattern = /[\w-]+@([\w-]+\.)+[\w-]+/i;
var match = pattern.test(string);
document.write(match);
Do note though that document.write
is frowned upon. You might rather want document.body.appendChild(document.createTextNode(match))
or something alike.