JS regex - convert "any" plain text hostname/url/ip to a link
I have been looking for a JS regexp that converts p开发者_StackOverflow中文版lain text url or hostnames to clickable links, but none of the script I found meet my requirements. Unfortunately, I suck at regex and are unable to modify the expression to work the way I want.
The plain text I wish to convert to links are:
- Anything staring with http(s):, ftp(s):, mailto: or file:
- domain.tld[:port][path][file][querystring]
- any.sub.domain.tld[:port][path][file][querystring]
- 0/255.0/255.0/255.0/255[:port][path][file][querystring]
- locahost[:port][path][file][querystring]
[*] = optional.
Any help are highly appreciated!
If you can live with false positives, such as something.notavalidtld
or 999.999.999.999
getting matched, what you are looking for is probably something like this. (Otherwise, it gets more messy.)
Start matching at the beginning of the string.
^(
Match anything starting with http/https/ftp/...
((https?|ftps?|mailto|file):.*?)
OR match the all of the below.
|
Optionally match http/https/ftp/... followed by :
and at least one /
.
((https?|ftps?|mailto|file):/+)?
Match an IP address...
(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
...or a domain (with optional username/password, which also matches email addresses)...
|([\w\d.:_%+-]+@)?([\w\d-]+\.)+[\w\d]{2,}
... or localhost
.
|localhost)
Optionally followed by a port number.
(:\d+)?
Optionally followed by any path/query string.
(/.*)?
Ensuring the string ends here.
)$
All the above parts should be joined together without any whitespace in between.
I haven't tested it extensively, so I might have missed something. But at least you have a starting point.
精彩评论