0

I am trying to use regex to validate a form in js, but I encountered a problem, which I could no google successfully.

When I create any RegExp in js, for example with the /(.)*/ the test function returns false no matter on what I test it... In php and regex online editors it works fine.

I tried to google it, but without any success, it seems as everyone is using the:

var regexp = /expression/

My code:

var reg = new RegExp("/(.)+/", "g");
console.log("Regexp:" + reg.test("a"));

Also I have been told that the regex in php should be compatible with the regex in js...

1
  • What does your regex test? Commented May 12, 2017 at 18:20

3 Answers 3

4

Your syntax is incorrect. You either need to remove the quotes, or remove the slashes. See the documentation here.

var reg = new RegExp(/(.)+/, "g");
console.log("Regexp:" + reg.test("a"));

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

2 Comments

Thank you, it works but is there any big difference between these two solutions? removing the quotes or removing the slashes?
It's basically run-time vs evaluation time compilation. Which becomes more apparent in a loop with a large number of iterations.
4

When you're using the RegExp object you shouldn't add / signs in the definitions. Simply use var reg = new RegExp("(.)+", "g");

2 Comments

Ty, it works, but also stackoverflow.com/a/43944221/5070552 works, is there any big difference?
Use literal notation when the regular expression will remain constant The Description section gives a pretty good explanation.
0

The major difference between JS and PHP Regex is: javascript : /[a-z]+/ php : '/[a-z]+/'

Simply the single quotes on each end of the regex expression.

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.