0

I have this code:

var regExp=new RegExp("(\/|-|.)+","g");

var t1=regExp.test(new Date());
alert(t1);//result true

var t2=regExp.test("19/03/1986");
alert(t1);//result true

why, first alert, return true value? There is not any charatter defined into regex pattern...

Thanks

4
  • 2
    . means any character. Also, you should learn about char class instead of using alternation groups Commented Oct 7, 2016 at 8:12
  • I guess . should be \. Commented Oct 7, 2016 at 8:12
  • And besdies, the g modifier should be removed if you only use the regex with RegExp#test. The new Date() is passed to the regex as "2016-10-07T08:13:59.703Z" string that your regex matches entirely (since it is equal to .+), that is why the second test also succeeds. Commented Oct 7, 2016 at 8:13
  • The first test would match even with "(/|-)+" or "(/|-|\\.)+" as there is a - inside the input. But you'd better use var regExp= /[-\/.]/; here. Commented Oct 7, 2016 at 9:20

2 Answers 2

1

. means any char in regexp, so any char can match your exp

you can change it to \d{4}(\/|-|\.)\d{2}(\/|-|\.)\d{2}

Maybe this can help you understand what you write

Regexper

enter image description here

and remove g

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

3 Comments

"may help you understand" should be a comment, not an answer. An answer should be clear and straight forward, not just inspiring.
Apologize, I have changed the anwser
No, . does not match any char in JS regex. Do you understand why g should be removed?
0

I found a solution:

var regExp= /(\/|-|\.)/g;
var t1=regExp.test(new Date());
alert(t1);// return false
var t2=regExp.test("19/03/1986");
alert(t2);// return true

Thanks

Comments

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.