Search code examples
javascriptregexvalidationurl

Regular expression for URL validation (in JavaScript)


Does someone have a regex for validating urls (NOT for finding them inside a text passage)? JavaScript snippet would be preferred.


Solution

  • The actual URL syntax is pretty complicated and not easy to represent in regex. Most of the simple-looking regexes out there will give many false negatives as well as false positives. See for amusement these efforts but even the end result is not good.

    Plus these days you would generally want to allow IRI as well as old-school URI, so we can link to valid addresses like:

    http://en.wikipedia.org/wiki/Þ
    http://例え.テスト/
    

    I would go only for simple checks: does it start with a known-good method: name? Is it free of spaces and double-quotes? If so then hell, it's probably good enough.