Tutorial :Regular expressions - javascript



Question:

I know this is a simple thing. but i just cant make it work.

Req: A word which contain at least one number, alphabets (can be both cases) and at least one symbol (special character).

In c# (?=.[0-9])(?=.[a-zA-z])(?=.*[!@#$%_]) worked. But in javascript its not working. Seems like it always look for number at the beginning since my condition starts with number in the regexp.f

Can anyone give me a regexp that can be used in javascript?

-Rakesh


Solution:1

JavaScript does support lookaheads. However, your groups expect that there's at least on character before the number and letter (because they start with just a dot .). Try adding a * to those two dots:

var pattern = /(?=.*[0-9])(?=.*[a-zA-z])(?=.*[!@#$%_])/;  pattern.test('xxx'); // false  pattern.test('111'); // false  pattern.test('!!!'); // false  pattern.test('x1!'); // true  

I'm seeing the same problem with this regular expression in C#, too.


Solution:2

Just to cover the obvious answer, given the requirements as stated I would use separate tests.

/[0-9]/.test(string) && /[a-z]/i.test(string) && /[!@#$%_]/.test(string)  

If you're interested in abstracting this away, one way is to store the tests in an array.

var tests = [ /[0-9]/, /[a-z]/i, /[!@#$%_]/ ];  

And one way to evaluate multiple tests without modifying the scope of surrounding code, simply shoehorning this into a closure, follows.

var passes = (function(){      for (var i=0; i<tests.length; i++)          if (!tests[i].test(string)) return false;      return true;  })();  


Solution:3

I don't think javascript supports those lookaheads. Try

/(.*[a-zA-Z].*[0-9].*[!@#$%_].*|.*[a-zA-Z].*[!@#$%_].*[0-9].*|.*[0-9].*[a-zA-Z].*[!@#$%_].*|.*[!@#$%_].*[a-zA-Z].*[0-9].*|.*[0-9].*[!@#$%_].*[a-zA-Z].*|.*[!@#$%_].*[0-9].*[a-zA-Z].*)/  

Not expecting any points for elegance...

Edit: As bdukes pointed out, js does support lookaheads. However, this (ugly) expression does work.


Solution:4

You can have a very long reg exp, with the three character classes repeated in differtent order, or use more than one test-

function teststring(s){   return /^[\da-zA-Z!@#$%_]+$/.test(s) &&   /\d/.test(s) && /[a-zA-Z]/.test(s) && /[!@#$%_]/.test(s);  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »