1

I try to build an Regular expression to check valid URL address. for now I tested different address and all was good , but those next (valid) address's failed:

    url = "http://example.com/tr/vvf/index.php/docs/po/trf"
   //url = "http://example-a.mydomain.com/test/ny" also not working

    var pattern = new RegExp("(https|ftp|http)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
    pattern.test(url)

I think because of the index.php/doc... Any ideas how to fix it

Dima
  • 443
  • 2
  • 9
  • 23
  • You need to escape the backslash one more time . Because your pattern is within double quotes and don't forget to use anchors while validating strings. – Avinash Raj Oct 29 '14 at 14:09
  • i don't think it's a good idea try to come up with a regex yourself matching url. matching url, password, etc should be viewed as an abusement of regex while people keep using it in this way. have a look at https://gist.github.com/gruber/8891611 and http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – Jason Hu Oct 29 '14 at 14:19

1 Answers1

0

Just use regex literal instead of RegExp object:

var pattern = /(https|ftp|http):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;

RegExp works with a string, that requires you to do double escaping so \w becomes \\w in it.

anubhava
  • 761,203
  • 64
  • 569
  • 643