Reputation: 119
I just noticed a very strange behaviour. Why does a simple space break all the tests?
rePattern = /^([a-z]+[-_]?){2,}[a-z]$/;
var test = new Array("jhgfg_hfh-g", "jhg-fg_hfhg", "jhg_fg_hfhg", "jhg_fg_hfhg", "jhg_fghfhg");
for (var i = 0; i < test.length ; i++) {
x = test[i];
alert(i + ' : ' + x + ' : ' + rePattern.test( x ));
}
if i change the above to
// notice {2,} => {2, } with an extra space before }
rePattern = /^([a-z]+[-_]?){2, }[a-z]$/;
then everything become false
...
thank u
Upvotes: 1
Views: 166
Reputation: 355
Your regexp does'nt work when you add a space at the begin or end of tested value because you use the regexp delemiters ^ and $
If you combine the two delimiters, the regexp will react to all the caracters including the spaces.
So use the following regexp to catch any string which following the pattern :
/([a-z]+[-_]?){2,}[a-z]/
Upvotes: 0
Reputation: 15351
OK, just to have an accepted answer here: it's because of the extra space. The syntax of regular expressions is strict, you can't add random whitespace and expect it'll be ignored. {2, }
will match literal {2, }
:
/^x{2, }$/.test('x{2, }') === true
Upvotes: 4