Samuel Kodytek
Samuel Kodytek

Reputation: 1024

REGEXP js dot not working

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...

Upvotes: 0

Views: 134

Answers (3)

Daniel Dwyer
Daniel Dwyer

Reputation: 11

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.

Upvotes: 0

Jordan Soltman
Jordan Soltman

Reputation: 3883

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"));

Upvotes: 4

Nhor
Nhor

Reputation: 3940

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

Upvotes: 4

Related Questions