2

I have a regular expression in java

^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!()*,/:;<>?\\\]\[\-_`{}~@#$%^&+=]).*$

It matches strings which having these conditions:

  • at least 8 characters
  • at least one digit
  • at least one small letter
  • at least one capital letter
  • at least one special character

    [!()*,/:;<>?\\\]\[\-_`{}~@#$%^&+=]
    

How can I convert it into a JavaScript regex?

3 Answers 3

3

Simple solution with simple regex.

var re = /^(.{0,7}|\D+|[^a-z]+|[^A-Z]+|[^\^!@#$%&\*])$/;
if (!re.test(str)) {
    alert('Matched');
}

Note that there are some missing special characters in my regex.

Sign up to request clarification or add additional context in comments.

3 Comments

It's a very good idea to see thing in negative way. But it's not giving exact result. Please see this jsfiddle.
Simple solution with simple regex that doesn't work. aaaaaaa
@BilalMirza You should escape - sign. updated jsfiddle
3

put two forward slashes around it:

var re = /<your_regex_here>/;

Comments

2

It already works in JavaScript:

var re = /^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!()*,/:;<>?\\\]\[\-_`{}~@#$%^&+=]).*$/;
re.test('abcdefgh0A$') // true

4 Comments

I hava a created a jsfiddle. All given strings are valid but it does not match some of strings. Am I missing something there?
@BilalMirza: First, a tip: use regular expression literals, like I did in the example with slashes - never new RegExp, which is almost always a bad idea. Next, no, they're not all valid... ptiLad4emp9, for example, does not contain a symbol.
You are right. that all strings are not valid. I wonder why did I noticed that. But why new RegExp() is a bad idea?
@BilalMirza: Just because you have to remember to escape everything, and it's also slightly slower (think eval).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.