Does someone have a regex for validating urls (NOT for finding them inside a text passage)? JavaScript snippet would be preferred.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:
or
or
References for syntax:
try with this:
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:
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.
Try this regex
It works best for me.
I've found some success with this:
It's obviously not perfect but it handled my cases pretty well